Inject useAsQuery function if no query and no id found.
@param   {Function}  fn      The function to be injected.
@returns {ViewBuilder} to be able to chain...
11280
function (fn) {
    if (!fn || !_.isFunction(fn)) {
      var err = new Error('Please pass a valid function!');
      debug(err);
      throw err;
    }

    if (fn.length === 2) {
      this.getQueryForThisViewBuilder = fn;
      return this;
    }

    this.getQueryForThisViewBuilder = function (evt, callback) {
      callback(null, fn(evt));
    };

    var unwrappedFn = this.getQueryForThisViewBuilder;

    this.getQueryForThisViewBuilder = function (evt, clb) {
      var wrappedCallback = function () {
        try {
          clb.apply(this, _.toArray(arguments));
        } catch (e) {
          debug(e);
          process.emit('uncaughtException', e);
        }
      };

      try {
        unwrappedFn.call(this, evt, wrappedCallback);
      } catch (e) {
        debug(e);
        process.emit('uncaughtException', e);
      }
    };

    return this;
  }
171536
function getProxy (select, property) {

    debug('property', property)

    // if property is then return a function that executes query calls
    // callbacks with result
    if (property === 'then') {
        // close where context
        closeWhereContext(select)
        // close order context
        closeOrderContext(select)
        // return function that will execute and return query
        return function (resolve, reject) {
            // debug query
            debug('then', select.query)
            // execute query
            return select.model.query(select.query).then(resolve).catch(err => {
                // call reject callback if set
                if (typeof reject === 'function') {
                    reject(err)
                }
                // otherwise return rejection
                else {
                    return Promise.reject(err)
                }
            })
        }
    }

    // if property is query then return function that executes query
    if (property === 'query') {
        // close where context
        closeWhereContext(select)
        // close order context
        closeOrderContext(select)
        // return function that will execute and return query
        return function (args) {
            // if args is set then merge args into query
            if (args) {
                _.merge(select.query, args)
            }
            // debug query
            debug('query', select.query)
            // execute query
            return select.model.query(select.query)
        }
    }

    // if property is views return function that gets names of views
    // then executes query
    if (property === 'view') {
        // close where context
        closeWhereContext(select)
        // close order context
        closeOrderContext(select)
        // return function that will execute and return query
        return function () {
            // names of views to apply
            var views
            // if first arg is array then use for views
            if (Array.isArray(arguments[0])) {
                views = arguments[0]
            }
            // otherwise copy arguments
            else {
                // create new array
                views = []
                // get number of arguments
                var length = arguments.length
                // copy view arguments
                for (var i=0; i < arguments.length; i++) {
                    views[i] = arguments[i]
                }
            }
            // add views to query
            select.query.view = views
            // debug query
            debug('query', select.query)
            // execute query
            return select.model.query(select.query)
        }
    }

    // add property to history
    select.history.push(property)

    /*
     * there are two primary selection contexts: where and by
     *
     * select by is more limited and only allows specifying a single column
     * to do a select where equals query on
     *
     * where context allows specifying multiple columns to match separated
     * by and with the full range of matching operators available.
     *
     * query modifiers can only be specified before any cotext is set - e.g.
     * one, all, current, allRevisions must be specified before by or where.
     *
     */

    // handle context specific logic
    if (!select.context) {
        // switch to by context
        if (property === 'by') {
            // set context
            select.context = 'by'
            // column name must follow by
            select.expectColumn = true
        }
        // switch to where context
        else if (property === 'where') {
            // set context
            select.context = 'where'
            // column name must follow where
            select.expectColumn = true
        }
        // switch to order context
        else if (property === 'order') {
            // set context
            select.context = 'order'
        }
        // set all flag on query
        else if (property === 'all') {
            select.query.all = true
        }
        // set allRevisions flag on query
        else if (property === 'allRevisions') {
            select.query.allRevisions = true
        }
        // set current flag on query
        else if (property === 'current') {
            select.query.current = true
        }
        // set limit: 1 on query
        else if (property === 'one') {
            select.query.limit = 1
        }
        // set required flag on query
        else if (property === 'required') {
            select.query.required = true
        }
        // set isCurrent flag on query
        else if (property === 'isCurrent') {
            select.query.isCurrent = true
        }
        // set resolve flag on query
        else if (property === 'resolve') {
            select.query.resolve = true
        }
        // set allow flag on query
        else if (property === 'allow') {
            select.query.allow = true
        }
        // set plain flag
        else if (property === 'plain') {
            select.query.plain = true
        }
        // invalid property
        else {
            throwInvalidProperty(property, select)
        }
    }
    else if (select.context === 'by') {
        // column is only allowed property after by
        var column = getColumn(property, select)
        // return function that will take select value and do query
        return function (val) {
            // if value is an array then always select all
            if (Array.isArray(val) && !select.query.one) {
                select.query.all = true
            }
            // otherwise if there is a single value and all is not specified
            // then limit query to a single (not-array) result
            else if (!select.query.all) {
                select.query.limit = 1
            }
            // set where clause for query
            select.query.where = {}
            select.query.where[column] = val
            // debug query
            debug('query', select.query)
            // execute query
            return select.model.query(select.query)
        }
    }
    else if (select.context === 'where') {
        // column must be first property in where clause
        if (select.expectColumn) {
            // property is an action isProperty
            if (property === 'isDeleted') {
                // isProperty takes place of column
                select.expectColumn = false
                // return function that captures value
                return function (value) {
                    // set isProperty as column for where query
                    select.contextData.column = property
                    select.contextData.operator = value
                    // add where clause to query
                    closeWhereContext(select)
                    // return proxy
                    return select.proxy
                }
            }
            else {
                // set column in context data
                select.contextData.column = getColumn(property, select)
            }
        }
        // otherwise look for operator
        else {
            // is is a noop
            if (property === 'is') {

            }
            // apply negation to where clause
            else if (property === 'not') {
                select.contextData.not = true
            }
            // property is valid match operator
            else if (matchOperators[property]) {
                select.contextData.operator = property
                // return function that captures value and then closes where
                return function (val) {
                    // capture value
                    select.contextData.value = val
                    // add where clause to query
                    closeWhereContext(select)
                    // return proxy
                    return select.proxy
                }
            }
            // property is null
            else if (property === 'null') {
                // set IS NULL operator
                select.contextData.operator = null
                // add where clause to query
                closeWhereContext(select)
            }
            // if doing and close current clause and start another
            else if (property === 'and') {
                // add where clause to query
                closeWhereContext(select)
                // next property should be column for new where clause
                select.expectColumn = true
            }
            // switch to order context
            else if (property === 'order') {
                // add where clause to query
                closeWhereContext(select)
                // set context
                select.context = 'order'
            }
            // switch to limit context - capture limit
            else if (property === 'limit') {
                // add where clause to query
                closeWhereContext(select)
                // set context
                select.context = 'limit'
                // return function that sets limit
                return function (val) {
                    // do not allow limit 1 after select.all
                    if (val === 1 && select.query.all) {
                        throwError('limit(1) not allowed with select.all', select)
                    }
                    // set limit
                    select.query.limit = val
                    // return proxy
                    return select.proxy
                }
            }
            else {
                throwInvalidProperty(property, select)
            }
        }
    }
    else if (select.context === 'order') {
        // by is a noop
        if (property === 'by') {
        }
        // switch to limit context - capture limit
        else if (property === 'limit') {
            // add context to query
            closeOrderContext(select)
            // set context
            select.context = 'limit'
            // return function that sets limit
            return function (val) {
                // do not allow limit 1 after select.all
                if (val === 1 && select.query.all) {
                    throwError('limit(1) not allowed with select.all', select)
                }
                // set limit
                select.query.limit = val
                // return proxy
                return select.proxy
            }
        }
        // direction asc|desc
        else if (property === 'asc' || property === 'desc') {
            // add direction to order context
            select.contextData.direction = property
            // add context to query
            closeOrderContext(select)
        }
        // if not keyword then expect column name
        else {
            // get column name
            var columnName = select.model.columnName(property)
            // throw error on invalid column name
            if (!columnName) {
                throwInvalidColumnName(columnName, select)
            }
            // if list of columns does not exist in context data create
            if (!select.contextData.columns) {
                select.contextData.columns = []
            }
            // add column to list of columns for order
            select.contextData.columns.push(columnName)
        }
    }
    else if (select.context === 'limit') {
        // capture offset
        if (property === 'offset') {
            // return function that sets offset
            return function (val) {
                // set offset
                select.query.offset = val
                // return proxy
                return select.proxy
            }
        }
        else {
            throwInvalidProperty(property, select)
        }
    }
    else {
        throwInvalidProperty(property, select)
    }

    // return proxy again for most cases
    return select.proxy
}
1357900
function(fn) {
    return function(req, res) {
	if (req.session.loggedin) {
	    return fn(req, res);
	} else {
	    res.redirect('/');
	}
    };
}
749338
function (fn) {
    !(showDialog === defaultShowDialog) ? invariant(false, 'The custom dialog was already injected.') : void 0;
    !(typeof fn === 'function') ? invariant(false, 'Injected showDialog() must be a function.') : void 0;
    showDialog = fn;
  }
274184
function (fn, update, container) {
  // Alias passed in variables for later access.
  this._fn        = fn;
  this._update    = update;
  this._container = container;

  // Assign every subscription instance a unique id. This helps with linking
  // between parent and child subscription instances.
  this.cid             = 'c' + Utils.uniqueId();
  this.children        = {};
  this.subscriptions   = {};
  this.unsubscriptions = [];

  // Create statically bound function instances for public consumption.
  this.boundUpdate         = Utils.bind(this.update, this);
  this.boundUnsubscription = Utils.bind(this.unsubscription, this);
}
1034367
function (queryKey, params, fn) {
    this.connection.query(templates[queryKey], params, function (err, result) {
      if (err) {
        fn(err, null);
      } else {
        fn(null, result.length ? result[0] : null);
      }
    });
  }
754278
function(callback){

    output("Initializing queries...");

    if(program.keyspace){
        batchQueries.unshift("USE " + program.keyspace + ";");
    }

    if(batchQueries && batchQueries.length > 0){
        output("Running queries...");
        executeQuery(batchQueries.shift(), callback);
    }else{
        callback("No queries to run.", null);
    }
}
949019
function(bson, ns, query, options) {
  var self = this;
  // Basic options needed to be passed in
  if (ns == null) throw new Error('ns must be specified for query');
  if (query == null) throw new Error('query must be specified for query');

  // Validate that we are not passing 0x00 in the collection name
  if (ns.indexOf('\x00') !== -1) {
    throw new Error('namespace cannot contain a null character');
  }

  // Basic options
  this.bson = bson;
  this.ns = ns;
  this.query = query;

  // Ensure empty options
  this.options = options || {};

  // Additional options
  this.numberToSkip = options.numberToSkip || 0;
  this.numberToReturn = options.numberToReturn || 0;
  this.returnFieldSelector = options.returnFieldSelector || null;
  this.requestId = Query.getRequestId();

  // special case for pre-3.2 find commands, delete ASAP
  this.pre32Limit = options.pre32Limit;

  // Serialization option
  this.serializeFunctions =
    typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  this.ignoreUndefined =
    typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false;
  this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16;
  this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true;
  this.batchSize = self.numberToReturn;

  // Flags
  this.tailable = false;
  this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false;
  this.oplogReplay = false;
  this.noCursorTimeout = false;
  this.awaitData = false;
  this.exhaust = false;
  this.partial = false;
}
1202764
function(object, callback) {
      return inject(object, null, function(state, key, value){
        if (state == undefined)
          return callIterator(callback, key, value) ? value : state
      })
    }
332562
function ViewBuilder (meta, denormFn) {
  Definition.call(this, meta);

  // used for replay...
  this.workerId = uuid().toString();

  meta = meta || {};

  if (!denormFn || (!_.isFunction(denormFn) && !_.isString(denormFn))) {
    var err = new Error('denormalizer function not injected!');
    debug(err);
    throw err;
  }

  if (_.isString(denormFn) && denormFn !== 'update' && denormFn !== 'create' && denormFn !== 'delete') {
    var err = new Error('denormalizer function "' + denormFn + '" not available! Use "create", "update" or "delete"!');
    debug(err);
    throw err;
  }

  this.version = meta.version || 0;
  this.payload = meta.payload === '' ? meta.payload : (meta.payload || null);
  this.aggregate = meta.aggregate || null;
  this.context = meta.context || null;
  this.id = meta.id || null;
  this.query = meta.query || null;
  this.autoCreate = meta.autoCreate === undefined || meta.autoCreate === null ? true : meta.autoCreate;
  this.priority = meta.priority || Infinity;

  if (_.isString(denormFn)) {
    if (denormFn === 'delete') {
      denormFn = function (evtData, vm) {
        vm.destroy();
      };
    } else {
      denormFn = function (evtData, vm) {
        vm.set(evtData);
      };
    }
  }

  this.denormFn = denormFn;

  if (denormFn.length === 2) {
    this.denormFn = function (evtData, vm, clb) {
      denormFn.call(this, evtData, vm);
      if (this.retryCalled) {
        return;
      }
      clb(null);
    };
  }

  var unwrappedDenormFn = this.denormFn;

  this.denormFn = function (evtData, vm, clb) {
    var wrappedCallback = function () {
      try {
        clb.apply(this, _.toArray(arguments));
      } catch (e) {
        debug(e);
        process.emit('uncaughtException', e);
      }
    };

    try {
      unwrappedDenormFn.call(this, evtData, vm, wrappedCallback.bind(this));
    } catch (e) {
      debug(e);
      process.emit('uncaughtException', e);
    }
  };

  this.idGenerator(function () {
    return uuid().toString();
  });

  this.defineShouldHandle(truthyShouldHandle);

  this.defineShouldHandleEvent(truthyShouldHandleEvent);  

  this.onAfterCommit(function (evt, vm) {});
}
1374945
function withPlugins(fn) {
  return function() {
    const args = Array.from(arguments);
    let plugins = (args[1] && args[1].plugins) || [];
    if (!isArray(plugins)) {
      plugins = Object.values(plugins);
    }
    args[1] = Object.assign({}, args[1], {
      plugins: internalPlugins.concat(plugins)
    });
    return fn.apply(null, args);
  };
}
609861
function(fn) {
      return function(key, value) {
        if (typeOf(key) == "object") {
          for (var i in key) {
            fn.call(this, i, key[i]);
          }
        } else {
          fn.call(this, key, value);
        }
        return this;
      };
    }
670870
function(ident, defFunc) {

	/**
	 * Here's the actual class we're making.
	 */
	var model = function(params) {
		var me = this;

		if (Object.keys(model.columns).length == 0) {
			logger.error("Attempting to initialize `" + model.ident + "` instance before filling schema!");
			return null;
		} else if (model.primary === undefined) {
			logger.error("No primary key found for `" + model.ident + "`!");
			return null;
		}

		Object.defineProperty(me, 'values', {
			value: {},
			enumerable: false,
			writable: true,
			configurable: true,
		}); // Raw column values, accessed by setter/getter functions.

		params = params || {};

		/* --- Instance Methods --- */

		/**
		 * Saves the object's properties corresponding to table columns into the database.
		 */
		function save() {
			var act = new NobleMachine(function() {
				setStrs = [];

				for (var key in model.columns) {
					if ([model.primary].indexOf(key) == -1 && me[key] !== undefined) {
						setStrs.push('`' + key + '`' + " = " + nrutil.serialize(me[key]));
					}
				}

				if (model.columns['updatedAt'])
					setStrs.push('`updatedAt` = NOW()');

				var sql;
				if (me[model.primary]) {
					sql = "UPDATE " + model.table
							+ " SET " + setStrs.join(',')
							+ " WHERE `" + model.primary + "` = " + me[model.primary];
				} else {
					if (model.columns['createdAt'])
						setStrs.push('`createdAt` = NOW()');

					sql = "INSERT"
							+ " INTO " + model.table
							+ " SET " + setStrs.join(',');
				}


				act.toNext(db_query(sql));
			});

			act.next(function(result) {
				//log.debug("RESULT: " + JSON.stringify(result));

				if (result.insert_id) {
					me[model.primary] = result.insert_id;
				} else if (!me[model.primary]) {
					act.toError("No insert_id, and no extant primary key!");
					return;
				}

				
				logger.log("Successfully saved `" + model.ident + "` record `" + me[model.primary] + "`");

				act.toNext(me);
			});

			act.error(function(err) {
				logger.error("Error saving `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		/**
		 * Reloads the object's properties with the current database values.
		 */
		function reload() {
			var params = {}

			params[model.primary] = me[model.primary]
		
			var act = new NobleMachine(model.find(params));

			act.next(function(newInst) {
				if (newInst) {
					for (var col in model.columns) {
						me[col] = newInst[col];
					}

					act.toNext(me);
				} else {
					for (var key in model.columns) {
						me[key] = undefined
					}

					act.toNext(null);
				}
			});

			return act;
		}

		/**
		 * Removes this object's corresponding database row.
		 */
		function destroy() {
			var act = new NobleMachine(function() {
				if (me.onDestroy) {
					var preact = me.onDestroy();
					if (preact && preact.start instanceof Function) {
						act.toNext(preact)
						return;
					}
				}
			});

			act.next(function() {
				var sql = "DELETE FROM " + model.table
						+ " WHERE `" + model.primary + "` = " + me[model.primary];

				act.toNext(db_query(sql));
			});

			act.next(function() {
				logger.log("Successfully deleted `" + model.ident + "` record `" + me[model.primary] + "`");

				for (var param in me) {
					delete me[param];	
				}
			});

			act.error(function(err) {
				logger.error("Error deleting `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		// Generic setter for SQL-correspondent values. Forces typecasting for database compatibility.
		function setValue(key, val) {
			//util.log(key + ": " + JSON.stringify(val));

			if (val === null) {
				me.values[key] = null;
			} else if (val === undefined) {
				me.values[key] = undefined;
			} else {
				type = model.columns[key]['DATA_TYPE'];

				switch (type) {
					case 'datetime':
					case 'timestamp':
						me.values[key] = new Date(val);
						break;
					case 'text':
					case 'varchar':
						me.values[key] = val.toString();
						break;
					case 'int':
					case 'tinyint':
						if (model.columns[key]['COLUMN_TYPE'] == 'tinyint(1)') {
							me.values[key] = !!val // Boolean
						} else {
							me.values[key] = parseInt(val);
						}
						break;
					default:
						me.values[key] = val;
				}
			}
		}

		// Generic getter for SQL-correspondent values.
		function getValue(key) {
			return me.values[key];
		}

		for (var key in model.columns) {
			me.__defineSetter__(key, setValue.bind(me, key));
			me.__defineGetter__(key, getValue.bind(me, key));

			if (params[key] !== undefined) {
				setValue(key, params[key]);
			}
		}

		_.extend(me, {
			save: save,
			reload: reload,
			destroy: destroy,
			setValue: setValue
		});

		if (defFunc !== undefined) {
			defFunc(me);
		}

		return me;
	}

	// This should be a unique, proper-cased identifier for the model as a whole.
	model.ident = ident;

	// Will be filled with INFORMATION_SCHEMA data.
	model.columns = {};

	// Guess the table name based on clever pluralization of the identifier.
	model.table = 'tbl' + ident.pluralize();

	/* --- Definition Methods --- */

	// Use this to override the default guess based on ident pluralization.
	model.setTableName = function(name) {
		model.table = name;
	}

	model.hasOne = function(foreignIdent) {
		model.prototype["get" + foreignIdent] = function() {
			var foreign = Models[foreignIdent];

			var opts = {}
			opts[model.primary] = this[model.primary];
			return foreign.find(opts);
		}
	}

	model.belongsTo = function(foreignIdent) {
		model.prototype["get" + foreignIdent] = function() {
			var foreign = Models[foreignIdent];

			var opts = {}
			opts[foreign.primary] = this[foreign.primary];
			return foreign.find(opts);
		}
	}

	/* --- Retrieval Methods --- */

	/**
	 * Executes a SELECT query on the table associated with this class and returns
	 * the result.
	 * @param where Qualifier to be passed to WHERE e.g "`this` = 'that'""
	 * @param fields Fields to return. Defaults to '*'.
	 */
	model.select = function(where, fields) {
		fields = fields || '*';

		var act = new NobleMachine(function() {
			var sql = "SELECT " + fields + " FROM " + model.table +
					  (where.length ? " WHERE " : '') + where + ";"

			act.toNext(db_query(sql));
		});

		act.next(function(result) {
			if (result.affected_rows == -1)
				act.toNext([]);
			else
				act.toNext(result.map(function(sqlobj) {
					return new model(sqlobj);
				}));
		});

		act.error(function(err) {
			logger.error("Error executing select statement for `" + model.ident +"`: " + JSON.stringify(err));
			act.emitError(err);
		});

		return act;
	}

	/**
     * A very simple SELECT query wrapper that returns a list of model instances.
	 * @param params Key-value pairs to be matched.
	 * @param conjunction Default 'AND'.
	 * @param fields Fields to return. Default in select().
     */
	model.where = function(params, conjunction, fields) {
		conjunction = conjunction || 'AND'
		var where = '';
		var first = true;

		logger.log("Finding all `" + model.ident + "`" + (params === undefined ? '' : " matching: " + util.inspect(params) + " with conjunction '" + conjunction + "'"));

		if (params) {
			for (var key in model.columns) {
				if (params[key] !== undefined) {
					where += (first ? '' : " " + conjunction + " ")
					if (params[key] == null) {
						where += "`" + key + "` IS NULL";
					} else {
						where += "`" + key + "` = " + nrutil.serialize(params[key]);
					}

					first = false;
				}
			}
		}

		return model.select(where, fields);
	}

	/**
	 * Emits first result from where() query
	 * @param params Params for find().
	 */
	model.find = function(params) {
		var act = new NobleMachine(function() {
			act.toNext(model.where(params));
		});

		act.next(function(objs) {
			act.toNext(objs.length ? objs[0] : null);
		});

		return act;
	}

	/**
	 * Retrieves every record of this type!
	 */
	model.all = function() {
		return model.where({});
	}

	/* --- Initialization Methods --- */

	/**
	 * This action queries the database to determine the structure of the table we are bound to.
	 */
	model.fillSchema = function() {
		var act = new NobleMachine(function() {
			var sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS"
					+ " WHERE TABLE_SCHEMA = '" + common.config.database.options.database + "'"
					+ " AND TABLE_NAME = '" + model.table + "';";

			act.toNext(db_query(sql));
		});

		act.next(function(res) {
			if (res.length == 0) {
				act.toError("No columns found for table `" + model.table + "`.");
				return;
			}

			res.forEach(function(col) {
				model.columns[col['COLUMN_NAME']] = col;

				if (col['COLUMN_KEY'] == 'PRI') { // Primary key!
					model.primary = col['COLUMN_NAME'];
				}
			});

			if (!model.primary) {
				act.toError("Could not detect primary key for table `" + model.table + "`.");
				return;
			}
		});

		return act;
	}

	Models[model.ident] = model;

	return model;
}
1271053
async function injectSauce(def) {
  debug(`checking ${def.base} for firefox`);
  if (def.browserName.toLowerCase().includes('firefox')) {
    debug('def is a firefox def');
    const platform = platformToShortName(def.platform);

    if (platform !== 'mac') {
      throw new Error(`No tooling implemented for injecting h264 into ${platform} (${def.platform})`);
    }

    debug(`injecting ${platform} profile into ${def.base}`);
    const dir = path.resolve(process.cwd(), `${PROFILE_DIR}/${platform}`);

    debug(`profile is at ${dir}`);
    const profile = await copy(dir);
    const encoded = await encode(profile);

    // eslint-disable-next-line camelcase
    def.firefox_profile = encoded;
    debug(`injected ${platform} profile into def`);
  }
}
472737
function _getCachedFunction(data, vars, relPath) {
  var func;
  if (app.viewCaching) {
      func = app.views.callbacks[relPath];
      if (func instanceof Function) { return func; }
      else { return null; }
  } else { return null; }
}
1100471
function(model, settings, options, cb) {
      var baseQuery, defaultSelect, k, query, v;
      if (settings == null) {
        settings = {};
      }
      if (options == null) {
        options = {};
      }
      if (cb == null) {
        cb = function() {};
      }
      Hoek.assert(model, i18n.assertModuleRequired);
      defaultSelect = settings.defaultSelect || null;
      baseQuery = settings.baseQuery || {};
      if (_.isFunction(options)) {
        cb = options;
        options = {};
      }
      options.where || (options.where = {});
      options.select || (options.select = defaultSelect);
      for (k in baseQuery) {
        v = baseQuery[k];
        options.where[k] = v;
      }
      query = model.findOne(options.where);
      if (options.select && options.select.length > 0) {
        query = query.select(options.select);
      }
      return query.exec(cb);
    }
1173104
function getHandler(fn) {
    if (isFunction(fn) && fn.actionHandler) {
        return function (req, res, next) {
            terminateMethods.map(function (method) {
                res[method] = getWrappedResponse(res[method]);
            });
            callHandler(fn, req, res, next);
        };
    } else {
        return fn;
    }
}