AbstractClass
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
Source codefunction AbstractClass(data) {
var self = this;
var ds = this.constructor.schema.definitions[this.constructor.modelName];
var properties = ds.properties;
var settings = ds.setings;
data = data || {};
if (data.id) {
defineReadonlyProp(this, 'id', data.id);
}
Object.defineProperty(this, 'cachedRelations', {
writable: true,
enumerable: false,
configurable: true,
value: {}
});
Object.keys(properties).forEach(function (attr) {
var _attr = '_' + attr,
attr_was = attr + '_was';
// Hidden property to store currrent value
Object.defineProperty(this, _attr, {
writable: true,
enumerable: false,
configurable: true,
value: isdef(data[attr]) ? data[attr] :
(isdef(this[attr]) ? this[attr] : (
getDefault(attr)
))
});
// Public setters and getters
Object.defineProperty(this, attr, {
get: function () {
if (this.constructor.getter[attr]) {
return this.constructor.getter[attr].call(this);
} else {
return this[_attr];
}
},
set: function (value) {
if (this.constructor.setter[attr]) {
this.constructor.setter[attr].call(this, value);
} else {
this[_attr] = value;
}
},
configurable: true,
enumerable: true
});
if (data.hasOwnProperty(attr)) {
// Getter for initial property
Object.defineProperty(this, attr_was, {
writable: true,
value: data[attr],
configurable: true,
enumerable: false
});
}
}.bind(this));
function getDefault(attr) {
var def = properties[attr]['default']
if (isdef(def)) {
if (typeof def === 'function') {
return def();
} else {
return def;
}
} else {
return null;
}
}
this.trigger("initialize");
};
Class methods Instance methods Helper methods AbstractClass.defineProperty
Declared as function (prop, params)
param String prop - property name
param Object params - various property configuration
Source codefunction (prop, params) {
this.schema.defineProperty(this.modelName, prop, params);
};
AbstractClass.create
Declared as function (data, callback)
Create new instance of Model class, saved in database
param data [optional]
param callback(err, obj)
callback called with arguments:
- err (null or Error)
- instance (null or Model)
Source codefunction (data, callback) {
if (stillConnecting(this.schema, this, arguments)) return;
var modelName = this.modelName;
if (typeof data === 'function') {
callback = data;
data = {};
}
if (typeof callback !== 'function') {
callback = function () {};
}
var obj = null;
// if we come from save
if (data instanceof AbstractClass && !data.id) {
obj = data;
data = obj.toObject(true);
// recall constructor to update _was property states (maybe bad idea)
this.call(obj, data);
create();
} else {
obj = new this(data);
data = obj.toObject(true);
// validation required
obj.isValid(function (valid) {
if (!valid) {
callback(new Error('Validation error'), obj);
} else {
create();
}
});
}
function create() {
obj.trigger('create', function (done) {
this._adapter().create(modelName, data, function (err, id) {
if (id) {
defineReadonlyProp(obj, 'id', id);
addToCache(this.constructor, obj);
}
done.call(this, function () {
if (callback) {
callback(err, obj);
}
});
}.bind(this));
});
}
};
AbstractClass.upsert
Declared as AbstractClass.updateOrCreate
Source codeAbstractClass.updateOrCreate{
if (stillConnecting(this.schema, this, arguments)) return;
var Model = this;
if (!data.id) return this.create(data, callback);
if (this.schema.adapter.updateOrCreate) {
this.schema.adapter.updateOrCreate(Model.modelName, data, function (err, data) {
var obj = data ? new Model(data) : null;
if (obj) {
addToCache(Model, obj);
}
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);
}
});
}
};
AbstractClass.exists
Declared as function exists(id, cb)
Check whether object exitst in database
param id id - identifier of object (primary key value)
param Function cb - callbacl called with (err, exists: Bool)
Source codefunction exists(id, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
if (id) {
this.schema.adapter.exists(this.modelName, id, cb);
} else {
cb(new Error('Model::exists requires positive id argument'));
}
};
AbstractClass.find
Declared as function find(id, cb)
Find object by id
param id id - primary key value
param Function cb - callback called with (err, instance)
Source codefunction find(id, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
this.schema.adapter.find(this.modelName, id, function (err, data) {
var obj = null;
if (data) {
var cached = getCached(this, data.id);
if (cached) {
obj = cached;
substractDirtyAttributes(obj, data);
this.call(obj, data);
} else {
data.id = id;
obj = new this(data);
addToCache(this, id);
}
}
cb(err, obj);
}.bind(this));
};
AbstractClass.all
Declared as function all(params, cb)
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'}}
- order: String
- limit: Number
- skip: Number
param Function callback (required) called with arguments:
- err (null or Error)
- Array of instances
Source codefunction all(params, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
if (arguments.length === 1) {
cb = params;
params = null;
}
var constr = this;
this.schema.adapter.all(this.modelName, params, function (err, data) {
var collection = null;
if (data && data.map) {
collection = data.map(function (d) {
var obj = null;
// do not create different instances for the same object
var cached = getCached(constr, d.id);
if (cached) {
obj = cached;
// keep dirty attributes untouthed (remove from dataset)
substractDirtyAttributes(obj, d);
constr.call(obj, d);
} else {
obj = new constr(d);
if (obj.id) addToCache(constr, obj);
}
return obj;
});
cb(err, collection);
}
});
};
AbstractClass.findOne
Declared as function findOne(params, cb)
Find one record, same as all
, limited by 1 and return object, not collection
param Object params - search conditions
param Function cb - callback called with (err, instance)
Source codefunction findOne(params, cb) {
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);
cb(err, collection[0]);
});
};
AbstractClass.destroyAll
Declared as function destroyAll(cb)
Destroy all records
param Function cb - callback called with (err)
Source codefunction destroyAll(cb) {
if (stillConnecting(this.schema, this, arguments)) return;
this.schema.adapter.destroyAll(this.modelName, function (err) {
clearCache(this);
cb(err);
}.bind(this));
};
AbstractClass.count
Declared as function (where, cb)
Return count of matched records
param Object where - search conditions (optional)
param Function cb - callback, called with (err, count)
Source codefunction (where, cb) {
if (stillConnecting(this.schema, this, arguments)) return;
if (typeof where === 'function') {
cb = where;
where = null;
}
this.schema.adapter.count(this.modelName, cb, where);
};
AbstractClass.toString
Declared as function ()
Return string representation of class
override default toString method
Source codefunction () {
return '[Model ' + this.modelName + ']';
}
AbstractClass.hasMany
Declared as function hasMany(anotherClass, params)
Declare hasMany relation
param Class anotherClass - class to has many
param Object params - configuration {as:, foreignKey:}
example User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
Source codefunction hasMany(anotherClass, params) {
var methodName = params.as; // or pluralize(anotherClass.modelName)
var fk = params.foreignKey;
// each instance of this class should have method named
// pluralize(anotherClass.modelName)
// which is actually just anotherClass.all({where: {thisModelNameId: this.id}}, cb);
defineScope(this.prototype, anotherClass, methodName, function () {
var x = {};
x[fk] = this.id;
return {where: x};
}, {
find: find,
destroy: destroy
});
// obviously, anotherClass should have attribute called `fk`
anotherClass.schema.defineForeignKey(anotherClass.modelName, fk);
function find(id, cb) {
anotherClass.find(id, function (err, inst) {
if (err) return cb(err);
if (inst[fk] === this.id) {
cb(null, inst);
} else {
cb(new Error('Permission denied'));
}
}.bind(this));
}
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'));
}
});
}
};
AbstractClass.belongsTo
Declared as function (anotherClass, params)
Declare belongsTo relation
param Class anotherClass - class to belong
param Object params - configuration {as: 'propertyName', foreignKey: 'keyName'}
Source codefunction (anotherClass, params) {
var methodName = params.as;
var fk = params.foreignKey;
this.schema.defineForeignKey(this.modelName, fk);
this.prototype['__finders__'] = this.prototype['__finders__'] || {}
this.prototype['__finders__'][methodName] = function (id, cb) {
anotherClass.find(id, function (err,inst) {
if (err) return cb(err);
if (inst[fk] === this.id) {
cb(null, inst);
} else {
cb(new Error('Permission denied'));
}
}.bind(this));
}
this.prototype[methodName] = function (p) {
if (p instanceof AbstractClass) { // acts as setter
this[fk] = p.id;
this.cachedRelations[methodName] = p;
} else if (typeof p === 'function') { // acts as async getter
this.__finders__[methodName](this[fk], p);
return this[fk];
} else if (typeof p === 'undefined') { // acts as sync getter
return this[fk];
} else { // setter
this[fk] = p;
}
};
};
AbstractClass.scope
Declared as function (name, params)
Define scope
TODO: describe behavior and usage examples
Source codefunction (name, params) {
defineScope(this, this, name, params);
};
AbstractClass.prototype.save
Declared as function (options, callback)
Save instance. When instance haven't id, create method called instead.
Triggers: validate, save, update | create
param options {validate: true, throws: false} [optional]
param callback(err, obj)
Source codefunction (options, callback) {
if (stillConnecting(this.constructor.schema, this, arguments)) return;
if (typeof options == 'function') {
callback = options;
options = {};
}
callback = callback || function () {};
options = options || {};
if (!('validate' in options)) {
options.validate = true;
}
if (!('throws' in options)) {
options.throws = false;
}
if (options.validate) {
this.isValid(function (valid) {
if (valid) {
save.call(this);
} else {
var err = new Error('Validation error');
// throws option is dangerous for async usage
if (options.throws) {
throw err;
}
callback(err, this);
}
}.bind(this));
} else {
save.call(this);
}
function save() {
this.trigger('save', function (saveDone) {
var modelName = this.constructor.modelName;
var data = this.toObject(true);
var inst = this;
if (inst.id) {
inst.trigger('update', function (updateDone) {
inst._adapter().save(modelName, data, function (err) {
if (err) {
console.log(err);
} else {
inst.constructor.call(inst, data);
}
updateDone.call(inst, function () {
saveDone.call(inst, function () {
callback(err, inst);
});
});
});
});
} else {
inst.constructor.create(inst, function (err) {
saveDone.call(inst, function () {
callback(err, inst);
});
});
}
});
}
};
AbstractClass.prototype._adapter
Declared as function ()
Return adapter of current record
private
Source codefunction () {
return this.constructor.schema.adapter;
};
AbstractClass.prototype.toObject
Declared as function (onlySchema)
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)
Source codefunction (onlySchema) {
var data = {};
var ds = this.constructor.schema.definitions[this.constructor.modelName];
var properties = ds.properties;
// weird
Object.keys(onlySchema ? properties : this).concat(['id']).forEach(function (property) {
data[property] = this[property];
}.bind(this));
return data;
};
AbstractClass.prototype.destroy
Declared as function (cb)
Delete object from persistence
triggers destroy
hook (async) before and after destroying object
Source codefunction (cb) {
if (stillConnecting(this.constructor.schema, this, arguments)) return;
this.trigger('destroy', function (destroyed) {
this._adapter().destroy(this.constructor.modelName, this.id, function (err) {
removeFromCache(this.constructor, this.id);
destroyed(function () {
cb && cb(err);
});
}.bind(this));
});
};
AbstractClass.prototype.updateAttribute
Declared as function updateAttribute(name, value, callback)
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)
Source codefunction updateAttribute(name, value, callback) {
data = {};
data[name] = value;
this.updateAttributes(data, callback);
};
AbstractClass.prototype.updateAttributes
Declared as function updateAttributes(data, cb)
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)
Source codefunction updateAttributes(data, cb) {
if (stillConnecting(this.constructor.schema, this, arguments)) return;
var inst = this;
var model = this.constructor.modelName;
// update instance's properties
Object.keys(data).forEach(function (key) {
inst[key] = data[key];
});
inst.isValid(function (valid) {
if (!valid) {
if (cb) {
cb(new Error('Validation error'));
}
} else {
update();
}
});
function update() {
inst.trigger('save', function (saveDone) {
inst.trigger('update', function (done) {
Object.keys(data).forEach(function (key) {
data[key] = inst[key];
});
inst._adapter().updateAttributes(model, inst.id, data, function (err) {
if (!err) {
inst.constructor.call(inst, data);
/*
Object.keys(data).forEach(function (key) {
inst[key] = data[key];
Object.defineProperty(inst, key + '_was', {
writable: false,
configurable: true,
enumerable: false,
value: data[key]
});
});
*/
}
done.call(inst, function () {
saveDone.call(inst, function () {
cb(err, inst);
});
});
});
});
});
}
};
AbstractClass.prototype.propertyChanged
Declared as function propertyChanged(attr)
Checks is property changed based on current property and initial value
param String attr - property name
return Boolean
Source codefunction propertyChanged(attr) {
return this['_' + attr] !== this[attr + '_was'];
};
AbstractClass.prototype.reload
Declared as function reload(callback)
Reload object from persistence
requires id
member of object
to be able to call find
param Function callback - called with (err, instance) arguments
Source codefunction reload(callback) {
if (stillConnecting(this.constructor.schema, this, arguments)) return;
var obj = getCached(this.constructor, this.id);
if (obj) obj.reset();
this.constructor.find(this.id, callback);
};
AbstractClass.prototype.reset
Declared as function ()
Reset dirty attributes
this method does not perform any database operation it just reset object to it's
initial state
Source codefunction () {
var obj = this;
Object.keys(obj).forEach(function (k) {
if (k !== 'id' && !obj.constructor.schema.definitions[obj.constructor.modelName].properties[k]) {
delete obj[k];
}
if (obj.propertyChanged(k)) {
obj[k] = obj[k + '_was'];
}
});
};
isdef
Declared as function isdef(s)
Check whether s
is not undefined
param Mixed s
return Boolean s is undefined
Source codefunction isdef(s) {
var undef;
return s !== undef;
}
merge
Declared as function merge(base, update)
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
Source codefunction merge(base, update) {
base = base || {};
if (update) {
Object.keys(update).forEach(function (key) {
base[key] = update[key];
});
}
return base;
}
defineReadonlyProp
Declared as function defineReadonlyProp(obj, key, value)
Define readonly property on object
param Object obj
param String key
param Mixed value
Source codefunction defineReadonlyProp(obj, key, value) {
Object.defineProperty(obj, key, {
writable: false,
enumerable: true,
configurable: true,
value: value
});
}
addToCache
Declared as function addToCache(constr, obj)
Source codefunction addToCache(constr, obj) {
touchCache(constr, obj.id);
constr.cache[obj.id] = obj;
}
touchCache
Declared as function touchCache(constr, id)
Renew object position in LRU cache index
Source codefunction touchCache(constr, id) {
var cacheLimit = constr.CACHE_LIMIT || DEFAULT_CACHE_LIMIT;
var ind = constr.mru.indexOf(id);
if (~ind) constr.mru.splice(ind, 1);
if (constr.mru.length >= cacheLimit * 2) {
for (var i = 0; i < cacheLimit;i += 1) {
delete constr.cache[constr.mru[i]];
}
constr.mru.splice(0, cacheLimit);
}
}
getCached
Declared as function getCached(constr, id)
Source codefunction getCached(constr, id) {
if (id) touchCache(constr, id);
return id && constr.cache[id];
}
clearCache
Declared as function clearCache(constr)
Clear cache (fully)
removes both cache and LRU index
param Class constr - class constructor
Source codefunction clearCache(constr) {
constr.cache = {};
constr.mru = [];
}
removeFromCache
Declared as function removeFromCache(constr, id)
Remove object from cache
param Class constr
param id id
Source codefunction removeFromCache(constr, id) {
var ind = constr.mru.indexOf(id);
if (!~ind) constr.mru.splice(ind, 1);
delete constr.cache[id];
}