loopback-datasource-juggler/lib/scope.js

354 lines
10 KiB
JavaScript
Raw Normal View History

var i8n = require('inflection');
var utils = require('./utils');
var defineCachedRelations = utils.defineCachedRelations;
var DefaultModelBaseClass = require('./model.js');
2013-04-11 23:23:34 +00:00
/**
* Module exports
*/
exports.defineScope = defineScope;
exports.mergeQuery = mergeQuery;
2013-04-11 23:23:34 +00:00
2014-06-16 17:50:42 +00:00
function ScopeDefinition(definition) {
2014-08-08 22:52:30 +00:00
this.isStatic = definition.isStatic;
this.modelFrom = definition.modelFrom;
this.modelTo = definition.modelTo || definition.modelFrom;
2014-06-16 17:50:42 +00:00
this.name = definition.name;
this.params = definition.params;
this.methods = definition.methods || {};
this.options = definition.options || {};
2014-06-16 17:50:42 +00:00
}
ScopeDefinition.prototype.targetModel = function(receiver) {
if (typeof this.options.modelTo === 'function') {
var modelTo = this.options.modelTo.call(this, receiver) || this.modelTo;
} else {
var modelTo = this.modelTo;
}
if (!(modelTo.prototype instanceof DefaultModelBaseClass)) {
var msg = 'Invalid target model for scope `';
msg += (this.isStatic ? this.modelFrom : this.modelFrom.constructor).modelName;
msg += this.isStatic ? '.' : '.prototype.';
msg += this.name + '`.';
throw new Error(msg);
}
return modelTo;
};
2014-06-16 17:50:42 +00:00
ScopeDefinition.prototype.related = function(receiver, scopeParams, condOrRefresh, cb) {
var name = this.name;
var self = receiver;
2014-07-27 14:30:45 +00:00
2014-06-16 17:50:42 +00:00
var actualCond = {};
var actualRefresh = false;
var saveOnCache = true;
if (arguments.length === 3) {
cb = condOrRefresh;
} else if (arguments.length === 4) {
if (typeof condOrRefresh === 'boolean') {
actualRefresh = condOrRefresh;
} else {
actualCond = condOrRefresh;
actualRefresh = true;
saveOnCache = false;
}
} else {
throw new Error('Method can be only called with one or two arguments');
}
if (!self.__cachedRelations || self.__cachedRelations[name] === undefined
|| actualRefresh) {
// It either doesn't hit the cache or refresh is required
2014-06-19 19:00:49 +00:00
var params = mergeQuery(actualCond, scopeParams);
var targetModel = this.targetModel(receiver);
return targetModel.find(params, function (err, data) {
2014-06-16 17:50:42 +00:00
if (!err && saveOnCache) {
defineCachedRelations(self);
self.__cachedRelations[name] = data;
}
cb(err, data);
});
} else {
// Return from cache
cb(null, self.__cachedRelations[name]);
}
}
/**
* Define a scope method
* @param {String} name of the method
* @param {Function} function to define
*/
ScopeDefinition.prototype.defineMethod = function(name, fn) {
return this.methods[name] = fn;
}
/**
* Define a scope to the class
* @param {Model} cls The class where the scope method is added
* @param {Model} targetClass The class that a query to run against
* @param {String} name The name of the scope
* @param {Object|Function} params The parameters object for the query or a function
* to return the query object
* @param methods An object of methods keyed by the method name to be bound to the class
*/
function defineScope(cls, targetClass, name, params, methods, options) {
2014-01-24 17:09:53 +00:00
// collect meta info about scope
if (!cls._scopeMeta) {
cls._scopeMeta = {};
}
2014-06-16 17:50:42 +00:00
// only makes sense to add scope in meta if base and target classes
2014-01-24 17:09:53 +00:00
// are same
if (cls === targetClass) {
cls._scopeMeta[name] = params;
} else if (targetClass) {
2014-01-24 17:09:53 +00:00
if (!targetClass._scopeMeta) {
targetClass._scopeMeta = {};
2013-04-11 23:23:34 +00:00
}
2014-01-24 17:09:53 +00:00
}
2014-08-08 22:52:30 +00:00
options = options || {};
// Check if the cls is the class itself or its prototype
var isStatic = (typeof cls === 'function') || options.isStatic || false;
2014-06-16 17:50:42 +00:00
var definition = new ScopeDefinition({
2014-08-08 22:52:30 +00:00
isStatic: isStatic,
modelFrom: cls,
modelTo: targetClass,
2014-06-16 17:50:42 +00:00
name: name,
params: params,
methods: methods,
options: options
2014-06-16 17:50:42 +00:00
});
2014-08-08 22:52:30 +00:00
if(isStatic) {
cls.scopes = cls.scopes || {};
cls.scopes[name] = definition;
} else {
cls.constructor.scopes = cls.constructor.scopes || {};
cls.constructor.scopes[name] = definition;
}
2014-01-24 17:09:53 +00:00
// Define a property for the scope
Object.defineProperty(cls, name, {
enumerable: false,
configurable: true,
/**
* This defines a property for the scope. For example, user.accounts or
* User.vips. Please note the cls can be the model class or prototype of
* the model class.
*
* The property value is function. It can be used to query the scope,
* such as user.accounts(condOrRefresh, cb) or User.vips(cb). The value
* can also have child properties for create/build/delete. For example,
* user.accounts.create(act, cb).
*
*/
get: function () {
var targetModel = definition.targetModel(this);
2014-03-13 23:43:38 +00:00
var self = this;
2014-06-16 17:50:42 +00:00
var f = function(condOrRefresh, cb) {
if(arguments.length === 1) {
definition.related(self, f._scope, condOrRefresh);
2014-01-24 17:09:53 +00:00
} else {
2014-06-16 17:50:42 +00:00
definition.related(self, f._scope, condOrRefresh, cb);
2013-04-11 23:23:34 +00:00
}
2014-01-24 17:09:53 +00:00
};
f._receiver = this;
2014-06-16 17:50:42 +00:00
f._scope = typeof definition.params === 'function' ?
definition.params.call(self) : definition.params;
f._targetClass = targetModel.modelName;
if (f._scope.collect) {
f._targetClass = i8n.capitalize(f._scope.collect);
}
2014-01-24 17:09:53 +00:00
f.build = build;
f.create = create;
f.destroyAll = destroyAll;
f.count = count;
2014-06-16 17:50:42 +00:00
for (var i in definition.methods) {
f[i] = definition.methods[i].bind(self);
2014-01-24 17:09:53 +00:00
}
if (!targetClass) return f;
2014-01-24 17:09:53 +00:00
2014-06-16 17:50:42 +00:00
// Define scope-chaining, such as
// Station.scope('active', {where: {isActive: true}});
// Station.scope('subway', {where: {isUndeground: true}});
// Station.active.subway(cb);
2014-01-24 17:09:53 +00:00
Object.keys(targetClass._scopeMeta).forEach(function (name) {
Object.defineProperty(f, name, {
enumerable: false,
get: function () {
mergeQuery(f._scope, targetModel._scopeMeta[name]);
2014-01-24 17:09:53 +00:00
return f;
}
});
2014-06-16 17:50:42 +00:00
}.bind(self));
2014-01-24 17:09:53 +00:00
return f;
}
});
// Wrap the property into a function for remoting
var fn = function () {
// primaryObject.scopeName, such as user.accounts
var f = this[name];
// set receiver to be the scope property whose value is a function
f.apply(this[name], arguments);
};
cls['__get__' + name] = fn;
var fn_create = function () {
var f = this[name].create;
f.apply(this[name], arguments);
};
cls['__create__' + name] = fn_create;
var fn_delete = function () {
var f = this[name].destroyAll;
f.apply(this[name], arguments);
};
cls['__delete__' + name] = fn_delete;
var fn_count = function (cb) {
var f = this[name].count;
f.apply(this[name], arguments);
};
cls['__count__' + name] = fn_count;
2014-06-19 19:00:49 +00:00
/*
* Extracting fixed property values for the scope from the where clause into
* the data object
*
* @param {Object} The data object
* @param {Object} The where clause
*/
function setScopeValuesFromWhere(data, where, targetModel) {
2014-06-19 19:00:49 +00:00
for (var i in where) {
if (i === 'and') {
// Find fixed property values from each subclauses
for (var w = 0, n = where[i].length; w < n; w++) {
setScopeValuesFromWhere(data, where[i][w], targetModel);
2014-06-19 19:00:49 +00:00
}
continue;
}
var prop = targetModel.definition.properties[i];
2014-06-19 19:00:49 +00:00
if (prop) {
var val = where[i];
if (typeof val !== 'object' || val instanceof prop.type
|| prop.type.name === 'ObjectID') // MongoDB key
{
2014-06-19 19:00:49 +00:00
// Only pick the {propertyName: propertyValue}
data[i] = where[i];
}
}
}
}
2014-01-24 17:09:53 +00:00
// and it should have create/build methods with binded thisModelNameId param
function build(data) {
2014-06-16 17:50:42 +00:00
data = data || {};
2014-06-19 19:00:49 +00:00
// Find all fixed property values for the scope
var targetModel = definition.targetModel(this._receiver);
2014-06-19 19:00:49 +00:00
var where = (this._scope && this._scope.where) || {};
setScopeValuesFromWhere(data, where, targetModel);
return new targetModel(data);
2014-01-24 17:09:53 +00:00
}
function create(data, cb) {
if (typeof data === 'function') {
cb = data;
data = {};
}
this.build(data).save(cb);
}
2014-01-24 17:09:53 +00:00
/*
Callback
- The callback will be called after all elements are destroyed
- For every destroy call which results in an error
- If fetching the Elements on which destroyAll is called results in an error
*/
function destroyAll(where, cb) {
if (typeof where === 'function') cb = where, where = {};
var scoped = (this._scope && this._scope.where) || {};
var filter = mergeQuery({ where: scoped }, { where: where || {} });
var targetModel = definition.targetModel(this._receiver);
targetModel.destroyAll(filter.where, cb);
2014-01-24 17:09:53 +00:00
}
function count(where, cb) {
if (typeof where === 'function') cb = where, where = {};
var scoped = (this._scope && this._scope.where) || {};
var filter = mergeQuery({ where: scoped }, { where: where || {} });
var targetModel = definition.targetModel(this._receiver);
targetModel.count(filter.where, cb);
}
2014-07-27 14:30:45 +00:00
return definition;
2014-06-16 17:50:42 +00:00
}
2013-04-11 23:23:34 +00:00
2014-06-16 17:50:42 +00:00
/*!
* Merge query parameters
2014-06-19 19:00:49 +00:00
* @param {Object} base The base object to contain the merged results
* @param {Object} update The object containing updates to be merged
* @returns {*|Object} The base object
2014-06-16 17:50:42 +00:00
* @private
*/
2014-06-19 19:00:49 +00:00
function mergeQuery(base, update) {
2014-06-16 17:50:42 +00:00
if (!update) {
return;
}
base = base || {};
2014-06-19 19:00:49 +00:00
if (update.where && Object.keys(update.where).length > 0) {
if (base.where && Object.keys(base.where).length > 0) {
base.where = {and: [base.where, update.where]};
} else {
base.where = update.where;
2013-04-11 23:23:34 +00:00
}
2014-06-16 17:50:42 +00:00
}
2013-04-11 23:23:34 +00:00
// Merge inclusion
2014-06-16 17:50:42 +00:00
if (update.include) {
if (!base.include) {
base.include = update.include;
} else {
var saved = base.include;
base.include = {};
base.include[update.include] = saved;
}
2014-06-16 17:50:42 +00:00
}
if (update.collect) {
base.collect = update.collect;
}
2013-04-11 23:23:34 +00:00
// set order
if (!base.order && update.order) {
2014-06-16 17:50:42 +00:00
base.order = update.order;
}
2014-06-16 17:50:42 +00:00
// overwrite pagination
if (update.limit !== undefined) {
base.limit = update.limit;
}
if (update.skip !== undefined) {
base.skip = update.skip;
}
if (update.offset !== undefined) {
base.offset = update.offset;
2014-01-24 17:09:53 +00:00
}
2013-04-11 23:23:34 +00:00
2014-06-16 17:50:42 +00:00
// Overwrite fields
if (update.fields !== undefined) {
base.fields = update.fields;
2014-01-24 17:09:53 +00:00
}
return base;
2013-04-11 23:23:34 +00:00
}