loopback-datasource-juggler/lib/model.js

1248 lines
37 KiB
JavaScript
Raw Normal View History

2011-10-10 13:22:51 +00:00
/**
2012-03-27 14:22:24 +00:00
* Module dependencies
2011-10-10 13:22:51 +00:00
*/
var util = require('util');
2013-03-26 00:39:47 +00:00
var i8n = require('inflection');
2013-03-24 21:27:36 +00:00
var jutil = require('./jutil.js');
var Validatable = require('./validations.js').Validatable;
var List = require('./list.js');
var Hookable = require('./hooks.js').Hookable;
var DEFAULT_CACHE_LIMIT = 1000;
2012-09-10 15:57:21 +00:00
var BASE_TYPES = ['String', 'Boolean', 'Number', 'Date', 'Text'];
2011-10-10 13:22:51 +00:00
exports.AbstractClass = AbstractClass;
AbstractClass.__proto__ = Validatable;
AbstractClass.prototype.__proto__ = Validatable.prototype;
jutil.inherits(AbstractClass, Hookable);
2011-10-10 13:22:51 +00:00
2011-10-08 17:11:26 +00:00
/**
2012-03-27 14:22:24 +00:00
* Abstract class - base class for all persist objects
* provides **common API** to access any database adapter.
* This class describes only abstract behavior layer, refer to `lib/adapters/*.js`
* to learn more about specific adapter implementations
*
* `AbstractClass` mixes `Validatable` and `Hookable` classes methods
*
* @constructor
* @param {Object} data - initial object data
2011-10-08 17:11:26 +00:00
*/
function AbstractClass(data) {
2012-04-19 15:01:40 +00:00
this._initProperties(data, true);
}
AbstractClass.prototype._initProperties = function (data, applySetters) {
2011-10-08 17:11:26 +00:00
var self = this;
2012-04-19 15:01:40 +00:00
var ctor = this.constructor;
var ds = ctor.schema.definitions[ctor.modelName];
2011-10-08 17:11:26 +00:00
var properties = ds.properties;
data = data || {};
2012-10-29 23:37:19 +00:00
Object.defineProperty(this, '__cachedRelations', {
writable: true,
enumerable: false,
configurable: true,
value: {}
});
Object.defineProperty(this, '__data', {
writable: true,
enumerable: false,
configurable: true,
value: {}
});
Object.defineProperty(this, '__dataWas', {
writable: true,
enumerable: false,
configurable: true,
value: {}
});
if (data['__cachedRelations']) {
this.__cachedRelations = data['__cachedRelations'];
}
for (var i in data) this.__data[i] = this.__dataWas[i] = data[i];
if (applySetters && ctor.setter) {
Object.keys(ctor.setter).forEach(function (attr) {
if (self.__data.hasOwnProperty(attr)) {
ctor.setter[attr].call(self, self.__data[attr]);
}
2011-10-08 17:11:26 +00:00
});
}
ctor.forEachProperty(function (attr) {
if ('undefined' === typeof self.__data[attr]) {
self.__data[attr] = self.__dataWas[attr] = getDefault(attr);
} else {
self.__dataWas[attr] = self.__data[attr];
}
});
ctor.forEachProperty(function (attr) {
2011-10-08 17:11:26 +00:00
2012-09-10 15:57:21 +00:00
var type = properties[attr].type;
if (BASE_TYPES.indexOf(type.name) === -1) {
if (typeof self.__data[attr] !== 'object' && self.__data[attr]) {
2012-09-11 16:51:31 +00:00
try {
self.__data[attr] = JSON.parse(self.__data[attr] + '');
2012-09-11 16:51:31 +00:00
} catch (e) {
self.__data[attr] = String(self.__data[attr]);
2012-09-10 15:57:21 +00:00
}
2012-09-11 16:51:31 +00:00
}
if (type.name === 'Array' || typeof type === 'object' && type.constructor.name === 'Array') {
self.__data[attr] = new List(self.__data[attr], type, self);
2012-09-10 15:57:21 +00:00
}
2012-05-29 11:16:24 +00:00
}
});
2011-10-11 19:51:32 +00:00
function getDefault(attr) {
2012-07-13 13:53:22 +00:00
var def = properties[attr]['default'];
2011-10-11 19:51:32 +00:00
if (isdef(def)) {
if (typeof def === 'function') {
return def();
} else {
return def;
}
} else {
return undefined;
2011-10-11 19:51:32 +00:00
}
}
this.trigger('initialize');
2012-07-13 13:53:22 +00:00
}
2011-10-08 17:11:26 +00:00
2012-03-27 14:22:24 +00:00
/**
* @param {String} prop - property name
* @param {Object} params - various property configuration
*/
2011-12-09 15:23:29 +00:00
AbstractClass.defineProperty = function (prop, params) {
this.schema.defineProperty(this.modelName, prop, params);
};
2012-01-18 15:20:05 +00:00
AbstractClass.whatTypeName = function (propName) {
var ds = this.schema.definitions[this.modelName];
2012-05-29 11:16:24 +00:00
return ds.properties[propName] && ds.properties[propName].type.name;
};
AbstractClass._forDB = function (data) {
var res = {};
Object.keys(data).forEach(function (propName) {
if (this.whatTypeName(propName) === 'JSON' || data[propName] instanceof Array) {
2012-05-29 11:16:24 +00:00
res[propName] = JSON.stringify(data[propName]);
} else {
res[propName] = data[propName];
}
}.bind(this));
return res;
2012-01-18 15:20:05 +00:00
};
AbstractClass.prototype.whatTypeName = function (propName) {
return this.constructor.whatTypeName(propName);
};
2011-10-08 17:11:26 +00:00
/**
2012-03-27 14:22:24 +00:00
* Create new instance of Model class, saved in database
*
2011-10-08 17:11:26 +00:00
* @param data [optional]
* @param callback(err, obj)
2012-03-27 14:22:24 +00:00
* callback called with arguments:
*
* - err (null or Error)
* - instance (null or Model)
2011-10-08 17:11:26 +00:00
*/
2012-01-27 08:48:37 +00:00
AbstractClass.create = function (data, callback) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
2013-03-31 09:40:37 +00:00
var Model = this;
var modelName = Model.modelName;
2011-10-08 17:11:26 +00:00
2012-01-27 08:48:37 +00:00
if (typeof data === 'function') {
callback = data;
2011-10-08 17:11:26 +00:00
data = {};
}
if (typeof callback !== 'function') {
callback = function () {};
}
2013-03-31 09:40:37 +00:00
if (data instanceof Array) {
var instances = [];
var errors = new Array(data.length);
var gotError = false;
var wait = data.length;
if (wait === 0) callback(null, []);
var instances = data.map(function(d, i) {
return Model.create(d, function(err, inst) {
// console.log('got', i, err, inst, inst.errors);
if (err) {
errors[i] = err;
gotError = true;
}
modelCreated();
});
});
return instances;
function modelCreated() {
if (--wait === 0) {
callback(gotError ? errors : null, instances);
}
}
}
var obj;
2011-10-10 13:22:51 +00:00
// if we come from save
2013-03-31 09:40:37 +00:00
if (data instanceof Model && !data.id) {
2011-10-08 17:11:26 +00:00
obj = data;
2011-10-10 13:22:51 +00:00
} else {
2013-03-31 09:40:37 +00:00
obj = new Model(data);
2011-10-08 17:11:26 +00:00
}
data = obj.toObject(true);
2011-10-08 17:11:26 +00:00
// validation required
obj.isValid(function(valid) {
if (valid) {
create();
} else {
callback(new Error('Validation error'), obj);
}
}, data);
function create() {
obj.trigger('create', function(createDone) {
obj.trigger('save', function(saveDone) {
this._adapter().create(modelName, this.constructor._forDB(data), function (err, id, rev) {
obj._initProperties(data, false);
if (id) {
obj.__data.id = id;
obj.__dataWas.id = id;
defineReadonlyProp(obj, 'id', id);
}
if (rev) {
obj._rev = rev
2011-11-20 05:36:15 +00:00
}
if (err) {
return callback(err, obj);
}
saveDone.call(obj, function () {
createDone.call(obj, function () {
callback(err, obj);
});
});
2011-11-20 05:36:15 +00:00
});
}, data);
}, data);
2011-11-19 08:58:49 +00:00
}
2013-03-30 17:06:09 +00:00
return obj;
2011-10-08 17:11:26 +00:00
};
2012-03-24 13:50:52 +00:00
function stillConnecting(schema, obj, args) {
if (schema.connected) return false;
var method = args.callee;
schema.on('connected', function () {
method.apply(obj, [].slice.call(args));
});
2012-03-25 11:37:44 +00:00
return true;
2012-03-24 13:50:52 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Update or insert
*/
2012-03-22 19:46:16 +00:00
AbstractClass.upsert = AbstractClass.updateOrCreate = function upsert(data, callback) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
2012-03-22 19:46:16 +00:00
var Model = this;
if (!data.id) return this.create(data, callback);
if (this.schema.adapter.updateOrCreate) {
2012-04-19 16:06:38 +00:00
var inst = new Model(data);
this.schema.adapter.updateOrCreate(Model.modelName, inst.toObject(), function (err, data) {
var obj;
if (data) {
inst._initProperties(data);
obj = inst;
} else {
obj = null;
}
2012-03-22 19:46:16 +00:00
callback(err, obj);
});
} else {
this.find(data.id, function (err, inst) {
if (err) return callback(err);
if (inst) {
inst.updateAttributes(data, callback);
} else {
var obj = new Model(data);
obj.save(data, callback);
}
});
}
};
/**
* Find one record, same as `all`, limited by 1 and return object, not collection,
* if not found, create using data provided as second argument
*
* @param {Object} query - search conditions: {where: {test: 'me'}}.
* @param {Object} data - object to create.
* @param {Function} cb - callback called with (err, instance)
*/
AbstractClass.findOrCreate = function findOrCreate(query, data, callback) {
if (typeof query === 'undefined') {
query = {where: {}};
}
if (typeof data === 'function' || typeof data === 'undefined') {
callback = data;
data = query && query.where;
}
if (typeof callback === 'undefined') {
callback = function () {};
}
var t = this;
this.findOne(query, function (err, record) {
if (err) return callback(err);
if (record) return callback(null, record);
t.create(data, callback);
});
};
2012-03-27 14:22:24 +00:00
/**
* Check whether object exitst in database
*
* @param {id} id - identifier of object (primary key value)
* @param {Function} cb - callbacl called with (err, exists: Bool)
*/
2011-10-08 17:11:26 +00:00
AbstractClass.exists = function exists(id, cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
2012-01-10 15:43:32 +00:00
if (id) {
this.schema.adapter.exists(this.modelName, id, cb);
} else {
cb(new Error('Model::exists requires positive id argument'));
}
2011-10-08 17:11:26 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Find object by id
*
* @param {id} id - primary key value
* @param {Function} cb - callback called with (err, instance)
*/
2011-10-08 17:11:26 +00:00
AbstractClass.find = function find(id, cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
2011-10-08 17:11:26 +00:00
this.schema.adapter.find(this.modelName, id, function (err, data) {
var obj = null;
if (data) {
if (!data.id) {
data.id = id;
}
obj = new this();
obj._initProperties(data, false);
2011-10-08 17:11:26 +00:00
}
cb(err, obj);
}.bind(this));
};
/**
2012-03-27 14:22:24 +00:00
* Find all instances of Model, matched by query
* make sure you have marked as `index: true` fields for filter or sort
*
* @param {Object} params (optional)
*
* - where: Object `{ key: val, key2: {gt: 'val2'}}`
* - include: String, Object or Array. See AbstractClass.include documentation.
2012-03-27 14:22:24 +00:00
* - order: String
* - limit: Number
* - skip: Number
*
* @param {Function} callback (required) called with arguments:
*
* - err (null or Error)
* - Array of instances
*/
AbstractClass.all = function all(params, cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
2011-10-08 17:11:26 +00:00
if (arguments.length === 1) {
cb = params;
params = null;
2011-10-08 17:11:26 +00:00
}
var constr = this;
this.schema.adapter.all(this.modelName, params, function (err, data) {
2011-10-08 17:11:26 +00:00
if (data && data.map) {
2012-10-13 14:25:50 +00:00
data.forEach(function (d, i) {
var obj = new constr;
obj._initProperties(d, false);
data[i] = obj;
2011-10-08 17:11:26 +00:00
});
if (data && data.countBeforeLimit) {
2012-10-16 09:12:34 +00:00
data.countBeforeLimit = data.countBeforeLimit;
}
cb(err, data);
2011-10-08 17:11:26 +00:00
}
else
cb(err, []);
2011-10-08 17:11:26 +00:00
});
};
2012-03-27 14:22:24 +00:00
/**
* Find one record, same as `all`, limited by 1 and return object, not collection
*
* @param {Object} params - search conditions: {where: {test: 'me'}}
2012-03-27 14:22:24 +00:00
* @param {Function} cb - callback called with (err, instance)
*/
AbstractClass.findOne = function findOne(params, cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
if (typeof params === 'function') {
cb = params;
params = {};
}
params.limit = 1;
this.all(params, function (err, collection) {
if (err || !collection || !collection.length > 0) return cb(err, null);
cb(err, collection[0]);
});
};
2011-11-23 06:05:11 +00:00
function substractDirtyAttributes(object, data) {
Object.keys(object.toObject()).forEach(function (attr) {
if (data.hasOwnProperty(attr) && object.propertyChanged(attr)) {
2011-11-23 06:05:11 +00:00
delete data[attr];
}
});
}
2012-03-27 14:22:24 +00:00
/**
* Destroy all records
* @param {Function} cb - callback called with (err)
*/
2011-10-08 17:11:26 +00:00
AbstractClass.destroyAll = function destroyAll(cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
2011-10-08 17:11:26 +00:00
this.schema.adapter.destroyAll(this.modelName, function (err) {
cb(err);
}.bind(this));
};
2012-03-27 14:22:24 +00:00
/**
* Return count of matched records
*
* @param {Object} where - search conditions (optional)
* @param {Function} cb - callback, called with (err, count)
*/
AbstractClass.count = function (where, cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.schema, this, arguments)) return;
if (typeof where === 'function') {
cb = where;
where = null;
}
this.schema.adapter.count(this.modelName, cb, where);
2011-10-08 17:11:26 +00:00
};
/**
* Allows you to load relations of several objects and optimize numbers of requests.
*
* @param {Array} objects - array of instances
* @param {String}, {Object} or {Array} include - which relations you want to load.
* @param {Function} cb - Callback called when relations are loaded
*
* Examples:
*
* - User.include(users, 'posts', function() {}); will load all users posts with only one additional request.
* - User.include(users, ['posts'], function() {}); // same
* - User.include(users, ['posts', 'passports'], function() {}); // will load all users posts and passports with two
* additional requests.
* - Passport.include(passports, {owner: 'posts'}, function() {}); // will load all passports owner (users), and all
* posts of each owner loaded
* - Passport.include(passports, {owner: ['posts', 'passports']}); // ...
* - Passport.include(passports, {owner: [{posts: 'images'}, 'passports']}); // ...
*
*/
AbstractClass.include = function (objects, include, cb) {
var self = this;
if (
(include.constructor.name == 'Array' && include.length == 0) ||
(include.constructor.name == 'Object' && Object.keys(include).length == 0)
) {
cb(null, objects);
return;
}
include = processIncludeJoin(include);
var keyVals = {};
var objsByKeys = {};
var nbCallbacks = 0;
for (var i = 0; i < include.length; i++) {
var callback = processIncludeItem(objects, include[i], keyVals, objsByKeys);
if (callback !== null) {
nbCallbacks++;
callback(function() {
nbCallbacks--;
if (nbCallbacks == 0) {
cb(null, objects);
}
});
2013-01-18 17:31:49 +00:00
} else {
cb(null, objects);
}
}
function processIncludeJoin(ij) {
if (typeof ij === 'string') {
ij = [ij];
}
if (ij.constructor.name === 'Object') {
var newIj = [];
for (var key in ij) {
var obj = {};
obj[key] = ij[key];
newIj.push(obj);
}
return newIj;
}
return ij;
}
function processIncludeItem(objs, include, keyVals, objsByKeys) {
var relations = self.relations;
if (include.constructor.name === 'Object') {
var relationName = Object.keys(include)[0];
var subInclude = include[relationName];
} else {
var relationName = include;
var subInclude = [];
}
var relation = relations[relationName];
if (!relation) {
return function() {
cb(new Error('Relation "' + relationName + '" is not defined for ' + self.modelName + ' model'));
}
}
var req = {'where': {}};
2012-12-16 17:20:39 +00:00
if (!keyVals[relation.keyFrom]) {
objsByKeys[relation.keyFrom] = {};
for (var j = 0; j < objs.length; j++) {
if (!objsByKeys[relation.keyFrom][objs[j][relation.keyFrom]]) {
objsByKeys[relation.keyFrom][objs[j][relation.keyFrom]] = [];
}
objsByKeys[relation.keyFrom][objs[j][relation.keyFrom]].push(objs[j]);
}
keyVals[relation.keyFrom] = Object.keys(objsByKeys[relation.keyFrom]);
}
if (keyVals[relation.keyFrom].length > 0) {
// deep clone is necessary since inq seems to change the processed array
2012-12-16 17:20:39 +00:00
var keysToBeProcessed = {};
var inValues = [];
for (var j = 0; j < keyVals[relation.keyFrom].length; j++) {
2012-12-16 17:20:39 +00:00
keysToBeProcessed[keyVals[relation.keyFrom][j]] = true;
if (keyVals[relation.keyFrom][j] !== 'null') {
inValues.push(keyVals[relation.keyFrom][j]);
}
}
req['where'][relation.keyTo] = {inq: inValues};
req['include'] = subInclude;
return function(cb) {
relation.modelTo.all(req, function(err, objsIncluded) {
for (var i = 0; i < objsIncluded.length; i++) {
delete keysToBeProcessed[objsIncluded[i][relation.keyTo]];
var objectsFrom = objsByKeys[relation.keyFrom][objsIncluded[i][relation.keyTo]];
for (var j = 0; j < objectsFrom.length; j++) {
if (!objectsFrom[j].__cachedRelations) {
objectsFrom[j].__cachedRelations = {};
}
if (relation.multiple) {
if (!objectsFrom[j].__cachedRelations[relationName]) {
objectsFrom[j].__cachedRelations[relationName] = [];
}
objectsFrom[j].__cachedRelations[relationName].push(objsIncluded[i]);
} else {
objectsFrom[j].__cachedRelations[relationName] = objsIncluded[i];
}
}
}
// No relation have been found for these keys
for (var key in keysToBeProcessed) {
var objectsFrom = objsByKeys[relation.keyFrom][key];
for (var j = 0; j < objectsFrom.length; j++) {
if (!objectsFrom[j].__cachedRelations) {
objectsFrom[j].__cachedRelations = {};
}
objectsFrom[j].__cachedRelations[relationName] = relation.multiple ? [] : null;
}
}
cb(err, objsIncluded);
});
};
}
return null;
}
}
2012-03-27 14:22:24 +00:00
/**
* Return string representation of class
*
* @override default toString method
*/
2011-10-08 17:11:26 +00:00
AbstractClass.toString = function () {
return '[Model ' + this.modelName + ']';
2012-07-13 13:53:22 +00:00
};
2011-10-08 17:11:26 +00:00
/**
* Save instance. When instance haven't id, create method called instead.
* Triggers: validate, save, update | create
2011-10-08 17:11:26 +00:00
* @param options {validate: true, throws: false} [optional]
* @param callback(err, obj)
*/
AbstractClass.prototype.save = function (options, callback) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.constructor.schema, this, arguments)) return;
2011-10-08 17:11:26 +00:00
if (typeof options == 'function') {
callback = options;
options = {};
}
2011-11-20 05:36:15 +00:00
callback = callback || function () {};
2011-11-21 21:34:15 +00:00
options = options || {};
2011-11-20 05:36:15 +00:00
2011-10-08 17:11:26 +00:00
if (!('validate' in options)) {
options.validate = true;
}
if (!('throws' in options)) {
options.throws = false;
}
var inst = this;
var data = inst.toObject(true);
var Model = this.constructor;
var modelName = Model.modelName;
if (!this.id) {
return Model.create(this, callback);
2011-11-19 08:58:49 +00:00
}
// validate first
if (!options.validate) {
return save();
}
inst.isValid(function (valid) {
if (valid) {
save();
} else {
var err = new Error('Validation error');
// throws option is dangerous for async usage
if (options.throws) {
throw err;
}
callback(err, inst);
}
});
// then save
2011-11-19 08:58:49 +00:00
function save() {
inst.trigger('save', function (saveDone) {
inst.trigger('update', function (updateDone) {
inst._adapter().save(modelName, inst.constructor._forDB(data), function (err) {
if (err) {
return callback(err, inst);
}
inst._initProperties(data, false);
updateDone.call(inst, function () {
saveDone.call(inst, function () {
callback(err, inst);
2011-11-20 05:36:15 +00:00
});
});
});
}, data);
}, data);
}
2011-10-08 17:11:26 +00:00
};
2011-10-10 13:22:51 +00:00
AbstractClass.prototype.isNewRecord = function () {
return !this.id;
};
2012-03-27 14:22:24 +00:00
/**
* Return adapter of current record
* @private
*/
2011-10-08 17:11:26 +00:00
AbstractClass.prototype._adapter = function () {
return this.constructor.schema.adapter;
};
2012-03-27 14:22:24 +00:00
/**
* Convert instance to Object
*
* @param {Boolean} onlySchema - restrict properties to schema only, default false
* when onlySchema == true, only properties defined in schema returned,
* otherwise all enumerable properties returned
* @returns {Object} - canonical object representation (no getters and setters)
*/
AbstractClass.prototype.toObject = function (onlySchema) {
2011-10-08 17:11:26 +00:00
var data = {};
var ds = this.constructor.schema.definitions[this.constructor.modelName];
var properties = ds.properties;
var self = this;
this.constructor.forEachProperty(function (attr) {
if (self[attr] instanceof List) {
data[attr] = self[attr].toObject();
} else if (self.__data.hasOwnProperty(attr)) {
data[attr] = self[attr];
2012-09-10 15:57:21 +00:00
} else {
data[attr] = null;
2012-09-10 15:57:21 +00:00
}
});
if (!onlySchema) {
Object.keys(self).forEach(function (attr) {
if (!data.hasOwnProperty(attr)) {
data[attr] = this[attr];
}
});
}
2011-10-08 17:11:26 +00:00
return data;
};
// AbstractClass.prototype.hasOwnProperty = function (prop) {
// return this.__data && this.__data.hasOwnProperty(prop) ||
// Object.getOwnPropertyNames(this).indexOf(prop) !== -1;
// };
2012-09-10 15:57:21 +00:00
AbstractClass.prototype.toJSON = function () {
return this.toObject();
};
2012-03-27 14:22:24 +00:00
/**
* Delete object from persistence
*
* @triggers `destroy` hook (async) before and after destroying object
*/
2011-10-08 17:11:26 +00:00
AbstractClass.prototype.destroy = function (cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.constructor.schema, this, arguments)) return;
2011-11-20 05:36:15 +00:00
this.trigger('destroy', function (destroyed) {
this._adapter().destroy(this.constructor.modelName, this.id, function (err) {
if (err) {
return cb(err);
}
2011-11-20 05:36:15 +00:00
destroyed(function () {
if(cb) cb();
2011-11-20 05:36:15 +00:00
});
}.bind(this));
});
2011-10-08 17:11:26 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Update single attribute
*
* equals to `updateAttributes({name: value}, cb)
*
* @param {String} name - name of property
* @param {Mixed} value - value of property
* @param {Function} callback - callback called with (err, instance)
*/
AbstractClass.prototype.updateAttribute = function updateAttribute(name, value, callback) {
2012-04-13 16:58:23 +00:00
var data = {};
2011-10-08 17:11:26 +00:00
data[name] = value;
2012-03-27 14:22:24 +00:00
this.updateAttributes(data, callback);
2011-10-08 17:11:26 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Update set of attributes
*
* this method performs validation before updating
*
* @trigger `validation`, `save` and `update` hooks
* @param {Object} data - data to update
* @param {Function} callback - callback called with (err, instance)
*/
2011-10-08 17:11:26 +00:00
AbstractClass.prototype.updateAttributes = function updateAttributes(data, cb) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.constructor.schema, this, arguments)) return;
2011-11-20 08:47:49 +00:00
var inst = this;
2011-10-08 17:11:26 +00:00
var model = this.constructor.modelName;
if (typeof data === 'function') {
cb = data;
data = null;
}
if (!data) {
data = {};
}
2012-12-19 18:29:14 +00:00
// update instance's properties
2011-10-10 13:22:51 +00:00
Object.keys(data).forEach(function (key) {
inst[key] = data[key];
});
inst.isValid(function (valid) {
if (!valid) {
if (cb) {
cb(new Error('Validation error'), inst);
}
} else {
inst.trigger('save', function (saveDone) {
inst.trigger('update', function (done) {
2011-11-20 08:47:49 +00:00
Object.keys(data).forEach(function (key) {
inst[key] = data[key];
});
inst._adapter().updateAttributes(model, inst.id, inst.constructor._forDB(data), function (err) {
if (!err) {
// update _was attrs
Object.keys(data).forEach(function (key) {
inst.__dataWas[key] = inst.__data[key];
});
}
done.call(inst, function () {
saveDone.call(inst, function () {
cb(err, inst);
});
2011-11-20 08:47:49 +00:00
});
});
}, data);
}, data);
}
}, data);
2011-10-08 17:11:26 +00:00
};
AbstractClass.prototype.fromObject = function (obj) {
Object.keys(obj).forEach(function (key) {
this[key] = obj[key];
}.bind(this));
};
2011-10-08 17:11:26 +00:00
/**
* Checks is property changed based on current property and initial value
2012-03-27 14:22:24 +00:00
*
* @param {String} attr - property name
2011-10-08 17:11:26 +00:00
* @return Boolean
*/
2012-03-27 14:22:24 +00:00
AbstractClass.prototype.propertyChanged = function propertyChanged(attr) {
return this.__data[attr] !== this.__dataWas[attr];
2011-10-08 17:11:26 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Reload object from persistence
*
* @requires `id` member of `object` to be able to call `find`
* @param {Function} callback - called with (err, instance) arguments
*/
AbstractClass.prototype.reload = function reload(callback) {
2012-03-24 13:50:52 +00:00
if (stillConnecting(this.constructor.schema, this, arguments)) return;
2012-03-27 14:22:24 +00:00
this.constructor.find(this.id, callback);
2011-10-08 17:11:26 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Reset dirty attributes
*
* this method does not perform any database operation it just reset object to it's
* initial state
*/
2011-11-28 16:31:01 +00:00
AbstractClass.prototype.reset = function () {
var obj = this;
Object.keys(obj).forEach(function (k) {
2011-12-11 08:58:34 +00:00
if (k !== 'id' && !obj.constructor.schema.definitions[obj.constructor.modelName].properties[k]) {
delete obj[k];
}
2011-11-28 16:31:01 +00:00
if (obj.propertyChanged(k)) {
obj[k] = obj[k + '_was'];
}
});
};
2012-03-27 14:22:24 +00:00
/**
* Declare hasMany relation
*
* @param {Class} anotherClass - class to has many
* @param {Object} params - configuration {as:, foreignKey:}
* @example `User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});`
*/
AbstractClass.hasMany = function hasMany(anotherClass, params) {
2013-03-26 00:39:47 +00:00
var thisClass = this, thisClassName = this.modelName;
params = params || {};
if (typeof anotherClass === 'string') {
params.as = anotherClass;
if (params.model) {
anotherClass = params.model;
} else {
var anotherClassName = i8n.singularize(anotherClass).toLowerCase();
for(var name in this.schema.models) {
if (name.toLowerCase() === anotherClassName) {
anotherClass = this.schema.models[name];
}
}
}
}
var methodName = params.as ||
i8n.camelize(i8n.pluralize(anotherClass.modelName), true);
var fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true);
2012-12-14 15:28:29 +00:00
this.relations[params['as']] = {
type: 'hasMany',
keyFrom: 'id',
2013-03-26 00:39:47 +00:00
keyTo: fk,
modelTo: anotherClass,
2012-12-14 15:28:29 +00:00
multiple: true
};
2011-10-08 17:11:26 +00:00
// each instance of this class should have method named
// pluralize(anotherClass.modelName)
2011-12-09 15:23:29 +00:00
// which is actually just anotherClass.all({where: {thisModelNameId: this.id}}, cb);
2011-10-15 15:57:35 +00:00
defineScope(this.prototype, anotherClass, methodName, function () {
var x = {};
x[fk] = this.id;
return {where: x};
2011-10-15 15:57:35 +00:00
}, {
find: find,
destroy: destroy
});
2011-10-08 17:11:26 +00:00
// obviously, anotherClass should have attribute called `fk`
anotherClass.schema.defineForeignKey(anotherClass.modelName, fk);
2011-10-15 15:57:35 +00:00
function find(id, cb) {
anotherClass.find(id, function (err, inst) {
if (err) return cb(err);
2012-04-11 15:36:10 +00:00
if (!inst) return cb(new Error('Not found'));
if (inst[fk] == this.id) {
2011-10-15 15:57:35 +00:00
cb(null, inst);
} else {
cb(new Error('Permission denied'));
}
}.bind(this));
}
2011-10-08 17:11:26 +00:00
2011-10-15 15:57:35 +00:00
function destroy(id, cb) {
this.find(id, function (err, inst) {
if (err) return cb(err);
if (inst) {
inst.destroy(cb);
} else {
cb(new Error('Not found'));
}
});
}
2011-10-08 17:11:26 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Declare belongsTo relation
*
* @param {Class} anotherClass - class to belong
* @param {Object} params - configuration {as: 'propertyName', foreignKey: 'keyName'}
*
* **Usage examples**
* Suppose model Post have a *belongsTo* relationship with User (the author of the post). You could declare it this way:
* Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
*
* When a post is loaded, you can load the related author with:
* post.author(function(err, user) {
* // the user variable is your user object
* });
*
* The related object is cached, so if later you try to get again the author, no additional request will be made.
* But there is an optional boolean parameter in first position that set whether or not you want to reload the cache:
* post.author(true, function(err, user) {
* // The user is reloaded, even if it was already cached.
* });
*
* This optional parameter default value is false, so the related object will be loaded from cache if available.
2012-03-27 14:22:24 +00:00
*/
2011-10-08 17:11:26 +00:00
AbstractClass.belongsTo = function (anotherClass, params) {
2013-03-26 20:48:14 +00:00
params = params || {};
if ('string' === typeof anotherClass) {
params.as = anotherClass;
if (params.model) {
anotherClass = params.model;
} else {
var anotherClassName = anotherClass.toLowerCase();
for(var name in this.schema.models) {
if (name.toLowerCase() === anotherClassName) {
anotherClass = this.schema.models[name];
}
2013-03-26 20:48:14 +00:00
}
}
}
var methodName = params.as || i8n.camelize(anotherClass.modelName, true);
var fk = params.foreignKey || methodName + 'Id';
2012-03-01 17:26:52 +00:00
2012-12-14 15:28:29 +00:00
this.relations[params['as']] = {
type: 'belongsTo',
keyFrom: fk,
2012-12-14 15:28:29 +00:00
keyTo: 'id',
modelTo: anotherClass,
2012-12-14 15:28:29 +00:00
multiple: false
};
2012-03-01 17:26:52 +00:00
this.schema.defineForeignKey(this.modelName, fk);
2012-07-13 13:53:22 +00:00
this.prototype['__finders__'] = this.prototype['__finders__'] || {};
this.prototype['__finders__'][methodName] = function (id, cb) {
if (id === null) {
cb(null, null);
return;
}
anotherClass.find(id, function (err,inst) {
if (err) return cb(err);
if (!inst) return cb(null, null);
if (inst.id === this[fk]) {
cb(null, inst);
} else {
cb(new Error('Permission denied'));
}
}.bind(this));
2012-07-13 13:53:22 +00:00
};
this.prototype[methodName] = function (refresh, p) {
if (arguments.length === 1) {
p = refresh;
refresh = false;
} else if (arguments.length > 2) {
throw new Error('Method can\'t be called with more than two arguments');
}
2012-10-29 23:37:19 +00:00
var self = this;
var cachedValue;
if (!refresh && this.__cachedRelations && (typeof this.__cachedRelations[methodName] !== 'undefined')) {
2012-10-29 23:37:19 +00:00
cachedValue = this.__cachedRelations[methodName];
}
2011-10-08 17:11:26 +00:00
if (p instanceof AbstractClass) { // acts as setter
this[fk] = p.id;
2012-10-29 23:37:19 +00:00
this.__cachedRelations[methodName] = p;
2011-10-08 17:11:26 +00:00
} else if (typeof p === 'function') { // acts as async getter
if (typeof cachedValue === 'undefined') {
this.__finders__[methodName].apply(self, [this[fk], function(err, inst) {
2012-10-29 23:37:19 +00:00
if (!err) {
self.__cachedRelations[methodName] = inst;
}
p(err, inst);
}]);
2012-10-29 23:37:19 +00:00
return this[fk];
} else {
p(null, cachedValue);
return cachedValue;
}
2012-03-01 17:26:52 +00:00
} else if (typeof p === 'undefined') { // acts as sync getter
return this[fk];
2012-03-01 17:26:52 +00:00
} else { // setter
this[fk] = p;
delete this.__cachedRelations[methodName];
2011-10-08 17:11:26 +00:00
}
2011-10-15 15:57:35 +00:00
};
2011-10-08 17:11:26 +00:00
};
2012-03-27 14:22:24 +00:00
/**
* Define scope
* TODO: describe behavior and usage examples
*/
2011-10-15 15:57:35 +00:00
AbstractClass.scope = function (name, params) {
defineScope(this, this, name, params);
};
function defineScope(cls, targetClass, name, params, methods) {
2011-10-15 15:57:35 +00:00
// collect meta info about scope
if (!cls._scopeMeta) {
cls._scopeMeta = {};
2011-10-15 15:57:35 +00:00
}
// only makes sence to add scope in meta if base and target classes
2011-10-15 15:57:35 +00:00
// are same
if (cls === targetClass) {
cls._scopeMeta[name] = params;
2011-10-15 15:57:35 +00:00
} else {
if (!targetClass._scopeMeta) {
targetClass._scopeMeta = {};
}
}
Object.defineProperty(cls, name, {
2011-10-15 15:57:35 +00:00
enumerable: false,
configurable: true,
get: function () {
2012-10-29 23:37:19 +00:00
var f = function caller(condOrRefresh, cb) {
var actualCond = {};
var actualRefresh = false;
var saveOnCache = true;
2011-10-15 15:57:35 +00:00
if (arguments.length === 1) {
2012-10-29 23:37:19 +00:00
cb = condOrRefresh;
2011-10-15 15:57:35 +00:00
} else if (arguments.length === 2) {
2012-10-29 23:37:19 +00:00
if (typeof condOrRefresh === 'boolean') {
actualRefresh = condOrRefresh;
} else {
actualCond = condOrRefresh;
actualRefresh = true;
saveOnCache = false;
2012-10-29 23:37:19 +00:00
}
2011-10-15 15:57:35 +00:00
} else {
throw new Error('Method can be only called with one or two arguments');
2011-10-15 15:57:35 +00:00
}
if (!this.__cachedRelations || (typeof this.__cachedRelations[name] == 'undefined') || actualRefresh) {
2012-10-29 23:37:19 +00:00
var self = this;
return targetClass.all(mergeParams(actualCond, caller._scope), function(err, data) {
if (!err && saveOnCache) {
self.__cachedRelations[name] = data;
}
2012-10-29 23:37:19 +00:00
cb(err, data);
});
} else {
cb(null, this.__cachedRelations[name]);
2012-10-29 23:37:19 +00:00
}
2011-10-15 15:57:35 +00:00
};
f._scope = typeof params === 'function' ? params.call(this) : params;
f.build = build;
f.create = create;
f.destroyAll = destroyAll;
for (var i in methods) {
2012-04-07 13:43:15 +00:00
f[i] = methods[i].bind(this);
2011-10-15 15:57:35 +00:00
}
// define sub-scopes
Object.keys(targetClass._scopeMeta).forEach(function (name) {
Object.defineProperty(f, name, {
enumerable: false,
get: function () {
mergeParams(f._scope, targetClass._scopeMeta[name]);
2011-10-15 15:57:35 +00:00
return f;
}
});
}.bind(this));
return f;
}
});
// and it should have create/build methods with binded thisModelNameId param
function build(data) {
return new targetClass(mergeParams(this._scope, {where:data || {}}).where);
2011-10-15 15:57:35 +00:00
}
function create(data, cb) {
if (typeof data === 'function') {
cb = data;
data = {};
}
this.build(data).save(cb);
}
2012-07-13 13:53:22 +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
*/
2012-03-21 11:12:13 +00:00
function destroyAll(cb) {
targetClass.all(this._scope, function (err, data) {
if (err) {
cb(err);
} else {
2012-07-13 13:53:22 +00:00
(function loopOfDestruction (data) {
if(data.length > 0) {
data.shift().destroy(function(err) {
if(err && cb) cb(err);
loopOfDestruction(data);
});
} else {
if(cb) cb();
}
}(data));
2012-03-21 11:12:13 +00:00
}
});
2011-10-15 15:57:35 +00:00
}
function mergeParams(base, update) {
if (update.where) {
base.where = merge(base.where, update.where);
}
// overwrite order
if (update.order) {
base.order = update.order;
}
return base;
}
2011-10-15 15:57:35 +00:00
}
2012-10-15 23:15:29 +00:00
AbstractClass.prototype.inspect = function () {
return util.inspect(this.__data, false, 4, true);
};
2012-03-27 14:22:24 +00:00
/**
* Check whether `s` is not undefined
* @param {Mixed} s
* @return {Boolean} s is undefined
*/
2011-10-08 17:11:26 +00:00
function isdef(s) {
var undef;
return s !== undef;
}
2012-03-27 14:22:24 +00:00
/**
* Merge `base` and `update` params
* @param {Object} base - base object (updating this object)
* @param {Object} update - object with new data to update base
* @returns {Object} `base`
*/
2011-10-08 17:11:26 +00:00
function merge(base, update) {
2011-10-15 15:57:35 +00:00
base = base || {};
if (update) {
Object.keys(update).forEach(function (key) {
base[key] = update[key];
});
}
2011-10-08 17:11:26 +00:00
return base;
}
2012-03-27 14:22:24 +00:00
/**
* Define readonly property on object
*
* @param {Object} obj
* @param {String} key
* @param {Mixed} value
*/
2011-10-08 17:11:26 +00:00
function defineReadonlyProp(obj, key, value) {
Object.defineProperty(obj, key, {
writable: false,
enumerable: true,
configurable: true,
value: value
});
}