2014-06-15 22:53:58 +00:00
|
|
|
/*!
|
|
|
|
* Dependencies
|
|
|
|
*/
|
|
|
|
var assert = require('assert');
|
|
|
|
var util = require('util');
|
|
|
|
var i8n = require('inflection');
|
|
|
|
var defineScope = require('./scope.js').defineScope;
|
2014-07-11 13:29:47 +00:00
|
|
|
var mergeQuery = require('./scope.js').mergeQuery;
|
2014-06-15 22:53:58 +00:00
|
|
|
var ModelBaseClass = require('./model.js');
|
2014-07-27 14:30:45 +00:00
|
|
|
var applyFilter = require('./connectors/memory').applyFilter;
|
|
|
|
var ValidationError = require('./validations.js').ValidationError;
|
2014-08-11 13:33:41 +00:00
|
|
|
var debug = require('debug')('loopback:relations');
|
2014-06-15 22:53:58 +00:00
|
|
|
|
|
|
|
exports.Relation = Relation;
|
|
|
|
exports.RelationDefinition = RelationDefinition;
|
|
|
|
|
|
|
|
var RelationTypes = {
|
|
|
|
belongsTo: 'belongsTo',
|
|
|
|
hasMany: 'hasMany',
|
|
|
|
hasOne: 'hasOne',
|
2014-07-27 14:30:45 +00:00
|
|
|
hasAndBelongsToMany: 'hasAndBelongsToMany',
|
2014-07-29 08:51:33 +00:00
|
|
|
referencesMany: 'referencesMany',
|
2014-08-19 20:10:35 +00:00
|
|
|
embedsOne: 'embedsOne',
|
2014-07-27 14:30:45 +00:00
|
|
|
embedsMany: 'embedsMany'
|
2014-06-15 22:53:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
exports.RelationTypes = RelationTypes;
|
|
|
|
exports.HasMany = HasMany;
|
|
|
|
exports.HasManyThrough = HasManyThrough;
|
|
|
|
exports.HasOne = HasOne;
|
|
|
|
exports.HasAndBelongsToMany = HasAndBelongsToMany;
|
|
|
|
exports.BelongsTo = BelongsTo;
|
2014-07-29 08:51:33 +00:00
|
|
|
exports.ReferencesMany = ReferencesMany;
|
2014-08-19 20:10:35 +00:00
|
|
|
exports.EmbedsOne = EmbedsOne;
|
2014-07-27 14:30:45 +00:00
|
|
|
exports.EmbedsMany = EmbedsMany;
|
2014-06-15 22:53:58 +00:00
|
|
|
|
|
|
|
var RelationClasses = {
|
|
|
|
belongsTo: BelongsTo,
|
|
|
|
hasMany: HasMany,
|
|
|
|
hasManyThrough: HasManyThrough,
|
|
|
|
hasOne: HasOne,
|
2014-07-27 14:30:45 +00:00
|
|
|
hasAndBelongsToMany: HasAndBelongsToMany,
|
2014-07-29 08:51:33 +00:00
|
|
|
referencesMany: ReferencesMany,
|
2014-08-19 20:10:35 +00:00
|
|
|
embedsOne: EmbedsOne,
|
2014-07-27 14:30:45 +00:00
|
|
|
embedsMany: EmbedsMany
|
2014-06-15 22:53:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
function normalizeType(type) {
|
|
|
|
if (!type) {
|
|
|
|
return type;
|
|
|
|
}
|
|
|
|
var t1 = type.toLowerCase();
|
|
|
|
for (var t2 in RelationTypes) {
|
|
|
|
if (t2.toLowerCase() === t1) {
|
|
|
|
return t2;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
2014-07-29 20:59:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
function extendScopeMethods(definition, scopeMethods, ext) {
|
2014-07-30 14:46:05 +00:00
|
|
|
var customMethods = [];
|
2014-07-29 20:59:44 +00:00
|
|
|
var relationClass = RelationClasses[definition.type];
|
|
|
|
if (definition.type === RelationTypes.hasMany && definition.modelThrough) {
|
|
|
|
relationClass = RelationClasses.hasManyThrough;
|
|
|
|
}
|
|
|
|
if (typeof ext === 'function') {
|
2014-07-30 14:46:05 +00:00
|
|
|
customMethods = ext.call(definition, scopeMethods, relationClass);
|
2014-07-29 20:59:44 +00:00
|
|
|
} else if (typeof ext === 'object') {
|
2014-08-13 09:28:23 +00:00
|
|
|
function createFunc(definition, relationMethod) {
|
|
|
|
return function() {
|
2014-07-29 20:59:44 +00:00
|
|
|
var relation = new relationClass(definition, this);
|
2014-07-30 15:30:21 +00:00
|
|
|
return relationMethod.apply(relation, arguments);
|
2014-07-29 20:59:44 +00:00
|
|
|
};
|
2014-08-13 09:28:23 +00:00
|
|
|
};
|
|
|
|
for (var key in ext) {
|
|
|
|
var relationMethod = ext[key];
|
|
|
|
var method = scopeMethods[key] = createFunc(definition, relationMethod);
|
2014-07-30 15:30:21 +00:00
|
|
|
if (relationMethod.shared) {
|
2014-08-01 09:24:41 +00:00
|
|
|
sharedMethod(definition, key, method, relationMethod);
|
2014-07-30 15:30:21 +00:00
|
|
|
}
|
2014-07-30 14:46:05 +00:00
|
|
|
customMethods.push(key);
|
2014-07-29 20:59:44 +00:00
|
|
|
}
|
|
|
|
}
|
2014-07-30 14:46:05 +00:00
|
|
|
return [].concat(customMethods || []);
|
2014-07-29 20:59:44 +00:00
|
|
|
};
|
2014-06-15 22:53:58 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Relation definition class. Use to define relationships between models.
|
|
|
|
* @param {Object} definition
|
|
|
|
* @class RelationDefinition
|
|
|
|
*/
|
|
|
|
function RelationDefinition(definition) {
|
|
|
|
if (!(this instanceof RelationDefinition)) {
|
|
|
|
return new RelationDefinition(definition);
|
|
|
|
}
|
|
|
|
definition = definition || {};
|
|
|
|
this.name = definition.name;
|
|
|
|
assert(this.name, 'Relation name is missing');
|
|
|
|
this.type = normalizeType(definition.type);
|
|
|
|
assert(this.type, 'Invalid relation type: ' + definition.type);
|
|
|
|
this.modelFrom = definition.modelFrom;
|
2014-06-21 18:44:33 +00:00
|
|
|
assert(this.modelFrom, 'Source model is required');
|
2014-06-15 22:53:58 +00:00
|
|
|
this.keyFrom = definition.keyFrom;
|
|
|
|
this.modelTo = definition.modelTo;
|
|
|
|
this.keyTo = definition.keyTo;
|
2014-08-15 10:55:10 +00:00
|
|
|
this.polymorphic = definition.polymorphic;
|
|
|
|
if (typeof this.polymorphic !== 'object') {
|
2014-07-26 10:47:55 +00:00
|
|
|
assert(this.modelTo, 'Target model is required');
|
|
|
|
}
|
2014-06-15 22:53:58 +00:00
|
|
|
this.modelThrough = definition.modelThrough;
|
|
|
|
this.keyThrough = definition.keyThrough;
|
|
|
|
this.multiple = (this.type !== 'belongsTo' && this.type !== 'hasOne');
|
2014-07-11 22:02:16 +00:00
|
|
|
this.properties = definition.properties || {};
|
2014-07-21 20:39:06 +00:00
|
|
|
this.options = definition.options || {};
|
2014-07-11 13:29:47 +00:00
|
|
|
this.scope = definition.scope;
|
2014-07-27 14:30:45 +00:00
|
|
|
this.embed = definition.embed === true;
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
RelationDefinition.prototype.toJSON = function () {
|
2014-08-16 08:23:32 +00:00
|
|
|
var polymorphic = typeof this.polymorphic === 'object';
|
|
|
|
|
|
|
|
var modelToName = this.modelTo && this.modelTo.modelName;
|
|
|
|
if (!modelToName && polymorphic && this.type === 'belongsTo') {
|
|
|
|
modelToName = '<polymorphic>';
|
|
|
|
}
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
var json = {
|
|
|
|
name: this.name,
|
|
|
|
type: this.type,
|
|
|
|
modelFrom: this.modelFrom.modelName,
|
|
|
|
keyFrom: this.keyFrom,
|
2014-08-16 08:23:32 +00:00
|
|
|
modelTo: modelToName,
|
2014-06-15 22:53:58 +00:00
|
|
|
keyTo: this.keyTo,
|
|
|
|
multiple: this.multiple
|
|
|
|
};
|
|
|
|
if (this.modelThrough) {
|
|
|
|
json.modelThrough = this.modelThrough.modelName;
|
|
|
|
json.keyThrough = this.keyThrough;
|
|
|
|
}
|
2014-08-16 08:23:32 +00:00
|
|
|
if (polymorphic) {
|
|
|
|
json.polymorphic = this.polymorphic;
|
|
|
|
}
|
2014-06-15 22:53:58 +00:00
|
|
|
return json;
|
|
|
|
};
|
|
|
|
|
2014-08-13 09:28:23 +00:00
|
|
|
/**
|
|
|
|
* Define a relation scope method
|
|
|
|
* @param {String} name of the method
|
|
|
|
* @param {Function} function to define
|
|
|
|
*/
|
|
|
|
RelationDefinition.prototype.defineMethod = function(name, fn) {
|
|
|
|
var relationClass = RelationClasses[this.type];
|
|
|
|
var relationName = this.name;
|
|
|
|
var modelFrom = this.modelFrom;
|
|
|
|
var definition = this;
|
|
|
|
var scope = this.modelFrom.scopes[this.name];
|
|
|
|
if (!scope) throw new Error('Unknown relation scope: ' + this.name);
|
|
|
|
var method = scope.defineMethod(name, function() {
|
|
|
|
var relation = new relationClass(definition, this);
|
|
|
|
return fn.apply(relation, arguments);
|
|
|
|
});
|
|
|
|
if (fn.shared) {
|
|
|
|
sharedMethod(definition, name, method, fn);
|
|
|
|
modelFrom.prototype['__' + name + '__' + relationName] = method;
|
|
|
|
}
|
|
|
|
return method;
|
|
|
|
};
|
|
|
|
|
2014-07-11 13:29:47 +00:00
|
|
|
/**
|
|
|
|
* Apply the configured scope to the filter/query object.
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @param {Object} filter (where, order, limit, fields, ...)
|
|
|
|
*/
|
|
|
|
RelationDefinition.prototype.applyScope = function(modelInstance, filter) {
|
2014-07-30 11:22:20 +00:00
|
|
|
filter = filter || {};
|
2014-07-26 10:47:55 +00:00
|
|
|
filter.where = filter.where || {};
|
2014-07-26 13:20:46 +00:00
|
|
|
if ((this.type !== 'belongsTo' || this.type === 'hasOne')
|
2014-08-15 10:55:10 +00:00
|
|
|
&& typeof this.polymorphic === 'object') { // polymorphic
|
|
|
|
var discriminator = this.polymorphic.discriminator;
|
|
|
|
if (this.polymorphic.invert) {
|
|
|
|
filter.where[discriminator] = this.modelTo.modelName;
|
|
|
|
} else {
|
|
|
|
filter.where[discriminator] = this.modelFrom.modelName;
|
|
|
|
}
|
2014-07-26 10:47:55 +00:00
|
|
|
}
|
2014-07-11 13:29:47 +00:00
|
|
|
if (typeof this.scope === 'function') {
|
|
|
|
var scope = this.scope.call(this, modelInstance, filter);
|
2014-07-26 10:47:55 +00:00
|
|
|
} else {
|
|
|
|
var scope = this.scope;
|
|
|
|
}
|
|
|
|
if (typeof scope === 'object') {
|
|
|
|
mergeQuery(filter, scope);
|
2014-07-11 13:29:47 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2014-07-11 22:02:16 +00:00
|
|
|
* Apply the configured properties to the target object.
|
2014-07-11 13:29:47 +00:00
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @param {Object} target
|
|
|
|
*/
|
2014-08-15 09:28:25 +00:00
|
|
|
RelationDefinition.prototype.applyProperties = function(modelInstance, obj) {
|
|
|
|
var source = modelInstance, target = obj;
|
|
|
|
if (this.options.invertProperties) {
|
|
|
|
source = obj, target = modelInstance;
|
|
|
|
}
|
2014-07-11 22:02:16 +00:00
|
|
|
if (typeof this.properties === 'function') {
|
2014-08-15 09:28:25 +00:00
|
|
|
var data = this.properties.call(this, source);
|
2014-07-11 13:29:47 +00:00
|
|
|
for(var k in data) {
|
|
|
|
target[k] = data[k];
|
|
|
|
}
|
2014-07-11 22:02:16 +00:00
|
|
|
} else if (typeof this.properties === 'object') {
|
|
|
|
for(var k in this.properties) {
|
|
|
|
var key = this.properties[k];
|
2014-08-15 09:28:25 +00:00
|
|
|
target[key] = source[k];
|
2014-07-11 13:29:47 +00:00
|
|
|
}
|
|
|
|
}
|
2014-07-26 13:20:46 +00:00
|
|
|
if ((this.type !== 'belongsTo' || this.type === 'hasOne')
|
2014-08-15 10:55:10 +00:00
|
|
|
&& typeof this.polymorphic === 'object') { // polymorphic
|
|
|
|
var discriminator = this.polymorphic.discriminator;
|
|
|
|
if (this.polymorphic.invert) {
|
|
|
|
target[discriminator] = this.modelTo.modelName;
|
|
|
|
} else {
|
|
|
|
target[discriminator] = this.modelFrom.modelName;
|
|
|
|
}
|
2014-07-26 10:47:55 +00:00
|
|
|
}
|
2014-07-11 13:29:47 +00:00
|
|
|
};
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/**
|
|
|
|
* A relation attaching to a given model instance
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {Relation}
|
|
|
|
* @constructor
|
|
|
|
* @class Relation
|
|
|
|
*/
|
|
|
|
function Relation(definition, modelInstance) {
|
|
|
|
if (!(this instanceof Relation)) {
|
|
|
|
return new Relation(definition, modelInstance);
|
|
|
|
}
|
|
|
|
if (!(definition instanceof RelationDefinition)) {
|
|
|
|
definition = new RelationDefinition(definition);
|
|
|
|
}
|
|
|
|
this.definition = definition;
|
|
|
|
this.modelInstance = modelInstance;
|
|
|
|
}
|
|
|
|
|
2014-06-21 18:44:33 +00:00
|
|
|
Relation.prototype.resetCache = function (cache) {
|
|
|
|
cache = cache || undefined;
|
|
|
|
this.modelInstance.__cachedRelations[this.definition.name] = cache;
|
|
|
|
};
|
|
|
|
|
|
|
|
Relation.prototype.getCache = function () {
|
|
|
|
return this.modelInstance.__cachedRelations[this.definition.name];
|
|
|
|
};
|
|
|
|
|
2014-08-13 09:28:23 +00:00
|
|
|
/**
|
|
|
|
* Fetch the related model(s) - this is a helper method to unify access.
|
|
|
|
* @param (Boolean|Object} condOrRefresh refresh or conditions object
|
|
|
|
* @param {Function} cb callback
|
|
|
|
*/
|
|
|
|
Relation.prototype.fetch = function(condOrRefresh, cb) {
|
|
|
|
this.modelInstance[this.definition.name].apply(this.modelInstance, arguments);
|
|
|
|
};
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/**
|
|
|
|
* HasMany subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {HasMany}
|
|
|
|
* @constructor
|
|
|
|
* @class HasMany
|
|
|
|
*/
|
|
|
|
function HasMany(definition, modelInstance) {
|
|
|
|
if (!(this instanceof HasMany)) {
|
|
|
|
return new HasMany(definition, modelInstance);
|
|
|
|
}
|
|
|
|
assert(definition.type === RelationTypes.hasMany);
|
|
|
|
Relation.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(HasMany, Relation);
|
|
|
|
|
2014-06-21 18:44:33 +00:00
|
|
|
HasMany.prototype.removeFromCache = function (id) {
|
|
|
|
var cache = this.modelInstance.__cachedRelations[this.definition.name];
|
|
|
|
var idName = this.definition.modelTo.definition.idName();
|
|
|
|
if (Array.isArray(cache)) {
|
|
|
|
for (var i = 0, n = cache.length; i < n; i++) {
|
|
|
|
if (cache[i][idName] === id) {
|
|
|
|
return cache.splice(i, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
};
|
|
|
|
|
|
|
|
HasMany.prototype.addToCache = function (inst) {
|
|
|
|
if (!inst) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
var cache = this.modelInstance.__cachedRelations[this.definition.name];
|
|
|
|
if (cache === undefined) {
|
|
|
|
cache = this.modelInstance.__cachedRelations[this.definition.name] = [];
|
|
|
|
}
|
|
|
|
var idName = this.definition.modelTo.definition.idName();
|
|
|
|
if (Array.isArray(cache)) {
|
|
|
|
for (var i = 0, n = cache.length; i < n; i++) {
|
|
|
|
if (cache[i][idName] === inst[idName]) {
|
|
|
|
cache[i] = inst;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
cache.push(inst);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/**
|
|
|
|
* HasManyThrough subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {HasManyThrough}
|
|
|
|
* @constructor
|
|
|
|
* @class HasManyThrough
|
|
|
|
*/
|
|
|
|
function HasManyThrough(definition, modelInstance) {
|
|
|
|
if (!(this instanceof HasManyThrough)) {
|
|
|
|
return new HasManyThrough(definition, modelInstance);
|
|
|
|
}
|
|
|
|
assert(definition.type === RelationTypes.hasMany);
|
|
|
|
assert(definition.modelThrough);
|
|
|
|
HasMany.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(HasManyThrough, HasMany);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* BelongsTo subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {BelongsTo}
|
|
|
|
* @constructor
|
|
|
|
* @class BelongsTo
|
|
|
|
*/
|
|
|
|
function BelongsTo(definition, modelInstance) {
|
|
|
|
if (!(this instanceof BelongsTo)) {
|
|
|
|
return new BelongsTo(definition, modelInstance);
|
|
|
|
}
|
|
|
|
assert(definition.type === RelationTypes.belongsTo);
|
|
|
|
Relation.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(BelongsTo, Relation);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* HasAndBelongsToMany subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {HasAndBelongsToMany}
|
|
|
|
* @constructor
|
|
|
|
* @class HasAndBelongsToMany
|
|
|
|
*/
|
|
|
|
function HasAndBelongsToMany(definition, modelInstance) {
|
|
|
|
if (!(this instanceof HasAndBelongsToMany)) {
|
|
|
|
return new HasAndBelongsToMany(definition, modelInstance);
|
|
|
|
}
|
|
|
|
assert(definition.type === RelationTypes.hasAndBelongsToMany);
|
|
|
|
Relation.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(HasAndBelongsToMany, Relation);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* HasOne subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {HasOne}
|
|
|
|
* @constructor
|
|
|
|
* @class HasOne
|
|
|
|
*/
|
|
|
|
function HasOne(definition, modelInstance) {
|
|
|
|
if (!(this instanceof HasOne)) {
|
|
|
|
return new HasOne(definition, modelInstance);
|
|
|
|
}
|
|
|
|
assert(definition.type === RelationTypes.hasOne);
|
|
|
|
Relation.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(HasOne, Relation);
|
|
|
|
|
2014-08-19 20:10:35 +00:00
|
|
|
/**
|
|
|
|
* EmbedsOne subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {EmbedsMany}
|
|
|
|
* @constructor
|
|
|
|
* @class EmbedsOne
|
|
|
|
*/
|
|
|
|
function EmbedsOne(definition, modelInstance) {
|
|
|
|
if (!(this instanceof EmbedsOne)) {
|
|
|
|
return new EmbedsMany(definition, modelInstance);
|
|
|
|
}
|
|
|
|
assert(definition.type === RelationTypes.embedsOne);
|
|
|
|
Relation.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(EmbedsOne, Relation);
|
|
|
|
|
2014-07-27 14:30:45 +00:00
|
|
|
/**
|
|
|
|
* EmbedsMany subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
|
|
|
* @returns {EmbedsMany}
|
|
|
|
* @constructor
|
|
|
|
* @class EmbedsMany
|
|
|
|
*/
|
|
|
|
function EmbedsMany(definition, modelInstance) {
|
|
|
|
if (!(this instanceof EmbedsMany)) {
|
|
|
|
return new EmbedsMany(definition, modelInstance);
|
|
|
|
}
|
|
|
|
assert(definition.type === RelationTypes.embedsMany);
|
|
|
|
Relation.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(EmbedsMany, Relation);
|
2014-06-15 22:53:58 +00:00
|
|
|
|
2014-07-29 08:51:33 +00:00
|
|
|
/**
|
|
|
|
* ReferencesMany subclass
|
|
|
|
* @param {RelationDefinition|Object} definition
|
|
|
|
* @param {Object} modelInstance
|
2014-07-29 19:46:12 +00:00
|
|
|
* @returns {ReferencesMany}
|
2014-07-29 08:51:33 +00:00
|
|
|
* @constructor
|
2014-07-29 19:46:12 +00:00
|
|
|
* @class ReferencesMany
|
2014-07-29 08:51:33 +00:00
|
|
|
*/
|
|
|
|
function ReferencesMany(definition, modelInstance) {
|
2014-07-29 19:46:12 +00:00
|
|
|
if (!(this instanceof ReferencesMany)) {
|
|
|
|
return new ReferencesMany(definition, modelInstance);
|
2014-07-29 08:51:33 +00:00
|
|
|
}
|
2014-07-29 19:46:12 +00:00
|
|
|
assert(definition.type === RelationTypes.referencesMany);
|
2014-07-29 08:51:33 +00:00
|
|
|
Relation.apply(this, arguments);
|
|
|
|
}
|
|
|
|
|
|
|
|
util.inherits(ReferencesMany, Relation);
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/*!
|
|
|
|
* Find the relation by foreign key
|
|
|
|
* @param {*} foreignKey The foreign key
|
|
|
|
* @returns {Object} The relation object
|
|
|
|
*/
|
2014-06-16 07:36:12 +00:00
|
|
|
function findBelongsTo(modelFrom, modelTo, keyTo) {
|
|
|
|
var relations = modelFrom.relations;
|
2014-06-15 22:53:58 +00:00
|
|
|
var keys = Object.keys(relations);
|
|
|
|
for (var k = 0; k < keys.length; k++) {
|
|
|
|
var rel = relations[keys[k]];
|
|
|
|
if (rel.type === RelationTypes.belongsTo &&
|
2014-06-16 07:36:12 +00:00
|
|
|
rel.modelTo === modelTo &&
|
2014-06-21 18:44:33 +00:00
|
|
|
(keyTo === undefined || rel.keyTo === keyTo)) {
|
2014-06-16 07:36:12 +00:00
|
|
|
return rel.keyFrom;
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Look up a model by name from the list of given models
|
|
|
|
* @param {Object} models Models keyed by name
|
|
|
|
* @param {String} modelName The model name
|
|
|
|
* @returns {*} The matching model class
|
|
|
|
*/
|
|
|
|
function lookupModel(models, modelName) {
|
|
|
|
if(models[modelName]) {
|
|
|
|
return models[modelName];
|
|
|
|
}
|
|
|
|
var lookupClassName = modelName.toLowerCase();
|
|
|
|
for (var name in models) {
|
|
|
|
if (name.toLowerCase() === lookupClassName) {
|
|
|
|
return models[name];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-09 08:58:03 +00:00
|
|
|
function lookupModelTo(modelFrom, modelTo, params, singularize) {
|
|
|
|
if ('string' === typeof modelTo) {
|
2014-08-16 08:23:32 +00:00
|
|
|
var modelToName;
|
2014-08-09 08:58:03 +00:00
|
|
|
params.as = params.as || modelTo;
|
|
|
|
modelTo = params.model || modelTo;
|
|
|
|
if (typeof modelTo === 'string') {
|
2014-08-16 08:23:32 +00:00
|
|
|
modelToName = (singularize ? i8n.singularize(modelTo) : modelTo).toLowerCase();
|
|
|
|
modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName) || modelTo;
|
|
|
|
}
|
|
|
|
if (typeof modelTo === 'string') {
|
|
|
|
modelToName = (singularize ? i8n.singularize(params.as) : params.as).toLowerCase();
|
2014-08-09 08:58:03 +00:00
|
|
|
modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName) || modelTo;
|
|
|
|
}
|
|
|
|
if (typeof modelTo !== 'function') {
|
2014-08-16 08:23:32 +00:00
|
|
|
throw new Error('Could not find "' + params.as + '" relation for ' + modelFrom.modelName);
|
2014-08-09 08:58:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return modelTo;
|
|
|
|
}
|
|
|
|
|
2014-07-28 08:44:26 +00:00
|
|
|
/*!
|
|
|
|
* Normalize polymorphic parameters
|
|
|
|
* @param {Object|String} params Name of the polymorphic relation or params
|
|
|
|
* @returns {Object} The normalized parameters
|
|
|
|
*/
|
|
|
|
function polymorphicParams(params) {
|
|
|
|
if (typeof params === 'string') params = { as: params };
|
|
|
|
if (typeof params.as !== 'string') params.as = 'reference'; // default
|
|
|
|
params.foreignKey = params.foreignKey || i8n.camelize(params.as + '_id', true);
|
|
|
|
params.discriminator = params.discriminator || i8n.camelize(params.as + '_type', true);
|
|
|
|
return params;
|
2014-07-28 21:22:45 +00:00
|
|
|
}
|
2014-07-28 08:44:26 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/**
|
|
|
|
* Define a "one to many" relationship by specifying the model name
|
|
|
|
*
|
|
|
|
* Examples:
|
|
|
|
* ```
|
|
|
|
* User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* ```
|
|
|
|
* Book.hasMany(Chapter);
|
|
|
|
* ```
|
|
|
|
* Or, equivalently:
|
|
|
|
* ```
|
|
|
|
* Book.hasMany('chapters', {model: Chapter});
|
|
|
|
* ```
|
|
|
|
* @param {Model} modelFrom Source model class
|
|
|
|
* @param {Object|String} modelTo Model object (or String name of model) to which you are creating the relationship.
|
|
|
|
* @options {Object} params Configuration parameters; see below.
|
|
|
|
* @property {String} as Name of the property in the referring model that corresponds to the foreign key field in the related model.
|
|
|
|
* @property {String} foreignKey Property name of foreign key field.
|
|
|
|
* @property {Object} model Model object
|
|
|
|
*/
|
|
|
|
RelationDefinition.hasMany = function hasMany(modelFrom, modelTo, params) {
|
|
|
|
var thisClassName = modelFrom.modelName;
|
|
|
|
params = params || {};
|
2014-08-09 08:58:03 +00:00
|
|
|
modelTo = lookupModelTo(modelFrom, modelTo, params, true);
|
2014-07-26 10:47:55 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
var relationName = params.as || i8n.camelize(modelTo.pluralModelName, true);
|
|
|
|
var fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true);
|
|
|
|
|
|
|
|
var idName = modelFrom.dataSource.idName(modelFrom.modelName) || 'id';
|
2014-08-15 10:55:10 +00:00
|
|
|
var discriminator, polymorphic;
|
2014-07-26 10:47:55 +00:00
|
|
|
|
2014-07-28 08:44:26 +00:00
|
|
|
if (params.polymorphic) {
|
2014-08-15 10:55:10 +00:00
|
|
|
polymorphic = polymorphicParams(params.polymorphic);
|
2014-08-16 08:23:32 +00:00
|
|
|
if (params.invert) polymorphic.invert = true;
|
2014-07-28 08:44:26 +00:00
|
|
|
discriminator = polymorphic.discriminator;
|
2014-07-26 19:11:25 +00:00
|
|
|
if (!params.invert) {
|
2014-07-28 08:44:26 +00:00
|
|
|
fk = polymorphic.foreignKey;
|
2014-07-26 19:11:25 +00:00
|
|
|
}
|
2014-07-26 10:47:55 +00:00
|
|
|
if (!params.through) {
|
2014-07-28 08:18:42 +00:00
|
|
|
modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, { type: 'string', index: true });
|
2014-07-26 10:47:55 +00:00
|
|
|
}
|
|
|
|
}
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
var definition = new RelationDefinition({
|
|
|
|
name: relationName,
|
|
|
|
type: RelationTypes.hasMany,
|
|
|
|
modelFrom: modelFrom,
|
|
|
|
keyFrom: idName,
|
|
|
|
keyTo: fk,
|
|
|
|
modelTo: modelTo,
|
2014-07-11 13:29:47 +00:00
|
|
|
multiple: true,
|
2014-07-11 22:02:16 +00:00
|
|
|
properties: params.properties,
|
2014-07-21 20:39:06 +00:00
|
|
|
scope: params.scope,
|
2014-08-15 10:55:10 +00:00
|
|
|
options: params.options,
|
|
|
|
polymorphic: polymorphic
|
2014-06-15 22:53:58 +00:00
|
|
|
});
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-07-26 12:54:54 +00:00
|
|
|
definition.modelThrough = params.through;
|
|
|
|
|
2014-09-02 13:57:24 +00:00
|
|
|
var keyThrough = params.keyThrough || i8n.camelize(modelTo.modelName + '_id', true);
|
2014-07-26 12:54:54 +00:00
|
|
|
definition.keyThrough = keyThrough;
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
modelFrom.relations[relationName] = definition;
|
|
|
|
|
|
|
|
if (!params.through) {
|
|
|
|
// obviously, modelTo should have attribute called `fk`
|
2014-07-26 10:47:55 +00:00
|
|
|
// for polymorphic relations, it is assumed to share the same fk type for all
|
|
|
|
// polymorphic models
|
2014-06-27 06:38:04 +00:00
|
|
|
modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var scopeMethods = {
|
|
|
|
findById: scopeMethod(definition, 'findById'),
|
2014-07-15 15:50:34 +00:00
|
|
|
destroy: scopeMethod(definition, 'destroyById'),
|
|
|
|
updateById: scopeMethod(definition, 'updateById'),
|
|
|
|
exists: scopeMethod(definition, 'exists')
|
|
|
|
};
|
|
|
|
|
|
|
|
var findByIdFunc = scopeMethods.findById;
|
|
|
|
modelFrom.prototype['__findById__' + relationName] = findByIdFunc;
|
|
|
|
|
|
|
|
var destroyByIdFunc = scopeMethods.destroy;
|
|
|
|
modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc;
|
|
|
|
|
|
|
|
var updateByIdFunc = scopeMethods.updateById;
|
|
|
|
modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc;
|
2014-06-15 22:53:58 +00:00
|
|
|
|
2014-07-28 09:36:32 +00:00
|
|
|
var existsByIdFunc = scopeMethods.exists;
|
|
|
|
modelFrom.prototype['__exists__' + relationName] = existsByIdFunc;
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
if(definition.modelThrough) {
|
|
|
|
scopeMethods.create = scopeMethod(definition, 'create');
|
|
|
|
scopeMethods.add = scopeMethod(definition, 'add');
|
|
|
|
scopeMethods.remove = scopeMethod(definition, 'remove');
|
|
|
|
|
2014-07-15 15:50:34 +00:00
|
|
|
var addFunc = scopeMethods.add;
|
|
|
|
modelFrom.prototype['__link__' + relationName] = addFunc;
|
|
|
|
|
|
|
|
var removeFunc = scopeMethods.remove;
|
|
|
|
modelFrom.prototype['__unlink__' + relationName] = removeFunc;
|
2014-06-27 06:38:04 +00:00
|
|
|
} else {
|
|
|
|
scopeMethods.create = scopeMethod(definition, 'create');
|
|
|
|
scopeMethods.build = scopeMethod(definition, 'build');
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-07-30 14:46:05 +00:00
|
|
|
var customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods);
|
|
|
|
|
|
|
|
for (var i = 0; i < customMethods.length; i++) {
|
|
|
|
var methodName = customMethods[i];
|
|
|
|
var method = scopeMethods[methodName];
|
|
|
|
if (typeof method === 'function' && method.shared === true) {
|
|
|
|
modelFrom.prototype['__' + methodName + '__' + relationName] = method;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
// Mix the property and scoped methods into the prototype class
|
|
|
|
defineScope(modelFrom.prototype, params.through || modelTo, relationName, function () {
|
|
|
|
var filter = {};
|
|
|
|
filter.where = {};
|
|
|
|
filter.where[fk] = this[idName];
|
2014-07-11 13:29:47 +00:00
|
|
|
|
|
|
|
definition.applyScope(this, filter);
|
2014-09-03 03:04:58 +00:00
|
|
|
|
|
|
|
// find corresponding belongsTo relations from through model as include
|
|
|
|
var include = [];
|
|
|
|
if (params.through) {
|
|
|
|
Object.keys(params.through.relations).forEach(function (rn) {
|
|
|
|
var relation = params.through.relations[rn];
|
|
|
|
|
|
|
|
// should be a belongsTo and match modelTo
|
|
|
|
if (relation.type === RelationTypes.belongsTo && relation.modelTo === modelTo) {
|
|
|
|
|
|
|
|
// should match keyThrough if specified
|
|
|
|
if (params.keyThrough && relation.keyFrom !== params.keyThrough) return;
|
|
|
|
|
|
|
|
if (include.indexOf(relation.name) === -1) {
|
|
|
|
include.push(relation.name);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2014-07-26 19:11:25 +00:00
|
|
|
if (params.through && params.polymorphic && params.invert) {
|
2014-07-28 08:18:42 +00:00
|
|
|
filter.where[discriminator] = modelTo.modelName; // overwrite
|
2014-07-26 19:11:25 +00:00
|
|
|
filter.collect = params.polymorphic;
|
|
|
|
filter.include = filter.collect;
|
|
|
|
} else if (params.through) {
|
2014-06-15 22:53:58 +00:00
|
|
|
filter.collect = i8n.camelize(modelTo.modelName, true);
|
2014-09-03 03:04:58 +00:00
|
|
|
filter.include = include;
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
2014-07-26 12:54:54 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
return filter;
|
2014-08-08 16:25:49 +00:00
|
|
|
}, scopeMethods, definition.options);
|
2014-08-13 09:28:23 +00:00
|
|
|
|
|
|
|
return definition;
|
2014-06-15 22:53:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
function scopeMethod(definition, methodName) {
|
2014-07-15 15:50:34 +00:00
|
|
|
var relationClass = RelationClasses[definition.type];
|
|
|
|
if (definition.type === RelationTypes.hasMany && definition.modelThrough) {
|
|
|
|
relationClass = RelationClasses.hasManyThrough;
|
|
|
|
}
|
2014-06-15 22:53:58 +00:00
|
|
|
var method = function () {
|
|
|
|
var relation = new relationClass(definition, this);
|
|
|
|
return relation[methodName].apply(relation, arguments);
|
|
|
|
};
|
2014-07-15 15:50:34 +00:00
|
|
|
|
|
|
|
var relationMethod = relationClass.prototype[methodName];
|
|
|
|
if (relationMethod.shared) {
|
2014-08-01 09:24:41 +00:00
|
|
|
sharedMethod(definition, methodName, method, relationMethod);
|
2014-07-15 15:50:34 +00:00
|
|
|
}
|
2014-06-15 22:53:58 +00:00
|
|
|
return method;
|
|
|
|
}
|
|
|
|
|
2014-08-01 09:24:41 +00:00
|
|
|
function sharedMethod(definition, methodName, method, relationMethod) {
|
|
|
|
method.shared = true;
|
|
|
|
method.accepts = relationMethod.accepts;
|
|
|
|
method.returns = relationMethod.returns;
|
|
|
|
method.http = relationMethod.http;
|
|
|
|
method.description = relationMethod.description;
|
|
|
|
};
|
|
|
|
|
2014-07-15 15:50:34 +00:00
|
|
|
/**
|
|
|
|
* Find a related item by foreign key
|
|
|
|
* @param {*} fkId The foreign key
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
HasMany.prototype.findById = function (fkId, cb) {
|
2014-06-15 22:53:58 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
2014-07-29 19:46:12 +00:00
|
|
|
var modelFrom = this.definition.modelFrom;
|
2014-06-15 22:53:58 +00:00
|
|
|
var fk = this.definition.keyTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
2014-07-15 15:50:34 +00:00
|
|
|
|
2014-07-11 13:29:47 +00:00
|
|
|
var idName = this.definition.modelTo.definition.idName();
|
|
|
|
var filter = {};
|
|
|
|
filter.where = {};
|
2014-07-15 15:50:34 +00:00
|
|
|
filter.where[idName] = fkId;
|
2014-07-11 13:29:47 +00:00
|
|
|
filter.where[fk] = modelInstance[pk];
|
|
|
|
|
2014-07-27 07:38:50 +00:00
|
|
|
if (filter.where[fk] === undefined) {
|
|
|
|
// Foreign key is undefined
|
|
|
|
return process.nextTick(cb);
|
|
|
|
}
|
2014-07-11 13:29:47 +00:00
|
|
|
this.definition.applyScope(modelInstance, filter);
|
|
|
|
|
|
|
|
modelTo.findOne(filter, function (err, inst) {
|
2014-06-15 22:53:58 +00:00
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
if (!inst) {
|
2014-07-15 15:50:34 +00:00
|
|
|
err = new Error('No instance with id ' + fkId + ' found for ' + modelTo.modelName);
|
|
|
|
err.statusCode = 404;
|
|
|
|
return cb(err);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
// Check if the foreign key matches the primary key
|
|
|
|
if (inst[fk] && inst[fk].toString() === modelInstance[pk].toString()) {
|
|
|
|
cb(null, inst);
|
|
|
|
} else {
|
2014-07-29 19:46:12 +00:00
|
|
|
err = new Error('Key mismatch: ' + modelFrom.modelName + '.' + pk
|
2014-07-15 15:50:34 +00:00
|
|
|
+ ': ' + modelInstance[pk]
|
|
|
|
+ ', ' + modelTo.modelName + '.' + fk + ': ' + inst[fk]);
|
|
|
|
err.statusCode = 400;
|
|
|
|
cb(err);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-07-15 15:50:34 +00:00
|
|
|
/**
|
|
|
|
* Find a related item by foreign key
|
|
|
|
* @param {*} fkId The foreign key
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
HasMany.prototype.exists = function (fkId, cb) {
|
2014-06-15 22:53:58 +00:00
|
|
|
var fk = this.definition.keyTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
2014-07-15 15:50:34 +00:00
|
|
|
|
2014-08-16 11:04:13 +00:00
|
|
|
this.findById(fkId, function (err, inst) {
|
2014-06-15 22:53:58 +00:00
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
if (!inst) {
|
2014-07-15 15:50:34 +00:00
|
|
|
return cb(null, false);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
// Check if the foreign key matches the primary key
|
|
|
|
if (inst[fk] && inst[fk].toString() === modelInstance[pk].toString()) {
|
2014-07-15 15:50:34 +00:00
|
|
|
cb(null, true);
|
2014-06-15 22:53:58 +00:00
|
|
|
} else {
|
2014-07-15 15:50:34 +00:00
|
|
|
cb(null, false);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update a related item by foreign key
|
|
|
|
* @param {*} fkId The foreign key
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
HasMany.prototype.updateById = function (fkId, data, cb) {
|
|
|
|
this.findById(fkId, function (err, inst) {
|
|
|
|
if (err) {
|
|
|
|
return cb && cb(err);
|
|
|
|
}
|
|
|
|
inst.updateAttributes(data, cb);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Delete a related item by foreign key
|
|
|
|
* @param {*} fkId The foreign key
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
HasMany.prototype.destroyById = function (fkId, cb) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-07-15 15:50:34 +00:00
|
|
|
this.findById(fkId, function(err, inst) {
|
2014-06-15 22:53:58 +00:00
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
2014-07-15 15:50:34 +00:00
|
|
|
self.removeFromCache(inst[fkId]);
|
2014-07-11 13:29:47 +00:00
|
|
|
inst.destroy(cb);
|
2014-06-15 22:53:58 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-07-26 15:20:25 +00:00
|
|
|
var throughKeys = function(definition) {
|
|
|
|
var modelThrough = definition.modelThrough;
|
|
|
|
var pk2 = definition.modelTo.definition.idName();
|
|
|
|
|
2014-08-15 10:55:10 +00:00
|
|
|
if (typeof definition.polymorphic === 'object') { // polymorphic
|
2014-07-26 15:20:25 +00:00
|
|
|
var fk1 = definition.keyTo;
|
2014-08-15 10:55:10 +00:00
|
|
|
if (definition.polymorphic.invert) {
|
|
|
|
var fk2 = definition.polymorphic.foreignKey;
|
|
|
|
} else {
|
|
|
|
var fk2 = definition.keyThrough;
|
|
|
|
}
|
2014-07-26 15:20:25 +00:00
|
|
|
} else {
|
|
|
|
var fk1 = findBelongsTo(modelThrough, definition.modelFrom,
|
|
|
|
definition.keyFrom);
|
|
|
|
var fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2);
|
|
|
|
}
|
|
|
|
return [fk1, fk2];
|
|
|
|
}
|
|
|
|
|
2014-07-15 15:50:34 +00:00
|
|
|
/**
|
|
|
|
* Find a related item by foreign key
|
|
|
|
* @param {*} fkId The foreign key value
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
HasManyThrough.prototype.findById = function (fkId, cb) {
|
|
|
|
var self = this;
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
var modelThrough = this.definition.modelThrough;
|
|
|
|
|
|
|
|
self.exists(fkId, function (err, exists) {
|
|
|
|
if (err || !exists) {
|
|
|
|
if (!err) {
|
|
|
|
err = new Error('No relation found in ' + modelThrough.modelName
|
|
|
|
+ ' for (' + self.definition.modelFrom.modelName + '.' + modelInstance[pk]
|
|
|
|
+ ',' + modelTo.modelName + '.' + fkId + ')');
|
|
|
|
err.statusCode = 404;
|
|
|
|
}
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
modelTo.findById(fkId, function (err, inst) {
|
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
if (!inst) {
|
|
|
|
err = new Error('No instance with id ' + fkId + ' found for ' + modelTo.modelName);
|
|
|
|
err.statusCode = 404;
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
cb(err, inst);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Delete a related item by foreign key
|
|
|
|
* @param {*} fkId The foreign key
|
|
|
|
* @param {Function} cb The callback function
|
|
|
|
*/
|
|
|
|
HasManyThrough.prototype.destroyById = function (fkId, cb) {
|
|
|
|
var self = this;
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
var modelThrough = this.definition.modelThrough;
|
|
|
|
|
|
|
|
self.exists(fkId, function (err, exists) {
|
|
|
|
if (err || !exists) {
|
|
|
|
if (!err) {
|
|
|
|
err = new Error('No record found in ' + modelThrough.modelName
|
|
|
|
+ ' for (' + self.definition.modelFrom.modelName + '.' + modelInstance[pk]
|
|
|
|
+ ' ,' + modelTo.modelName + '.' + fkId + ')');
|
|
|
|
err.statusCode = 404;
|
|
|
|
}
|
|
|
|
return cb(err);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
2014-07-15 15:50:34 +00:00
|
|
|
self.remove(fkId, function(err) {
|
|
|
|
if(err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
modelTo.deleteById(fkId, cb);
|
|
|
|
});
|
2014-06-15 22:53:58 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
// Create an instance of the target model and connect it to the instance of
|
|
|
|
// the source model by creating an instance of the through model
|
|
|
|
HasManyThrough.prototype.create = function create(data, done) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-06-16 07:36:12 +00:00
|
|
|
var definition = this.definition;
|
|
|
|
var modelTo = definition.modelTo;
|
|
|
|
var modelThrough = definition.modelThrough;
|
2014-07-26 12:54:54 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
if (typeof data === 'function' && !done) {
|
|
|
|
done = data;
|
|
|
|
data = {};
|
|
|
|
}
|
|
|
|
|
2014-06-16 07:36:12 +00:00
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
// First create the target model
|
2014-06-21 18:44:33 +00:00
|
|
|
modelTo.create(data, function (err, to) {
|
2014-06-15 22:53:58 +00:00
|
|
|
if (err) {
|
2014-06-21 18:44:33 +00:00
|
|
|
return done && done(err, to);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
2014-06-16 07:36:12 +00:00
|
|
|
// The primary key for the target model
|
2014-06-21 18:44:33 +00:00
|
|
|
var pk2 = definition.modelTo.definition.idName();
|
2014-07-26 12:54:54 +00:00
|
|
|
|
2014-07-26 15:20:25 +00:00
|
|
|
var keys = throughKeys(definition);
|
|
|
|
var fk1 = keys[0];
|
|
|
|
var fk2 = keys[1];
|
2014-07-26 12:54:54 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
var d = {};
|
2014-06-16 07:36:12 +00:00
|
|
|
d[fk1] = modelInstance[definition.keyFrom];
|
2014-06-21 18:44:33 +00:00
|
|
|
d[fk2] = to[pk2];
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-07-11 22:02:16 +00:00
|
|
|
definition.applyProperties(modelInstance, d);
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
// Then create the through model
|
2014-06-21 18:44:33 +00:00
|
|
|
modelThrough.create(d, function (e, through) {
|
2014-06-15 22:53:58 +00:00
|
|
|
if (e) {
|
|
|
|
// Undo creation of the target model
|
2014-06-21 18:44:33 +00:00
|
|
|
to.destroy(function () {
|
2014-06-15 22:53:58 +00:00
|
|
|
done && done(e);
|
|
|
|
});
|
|
|
|
} else {
|
2014-06-21 18:44:33 +00:00
|
|
|
self.addToCache(to);
|
|
|
|
done && done(err, to);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-07-26 15:20:25 +00:00
|
|
|
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/**
|
|
|
|
* Add the target model instance to the 'hasMany' relation
|
|
|
|
* @param {Object|ID} acInst The actual instance or id value
|
|
|
|
*/
|
|
|
|
HasManyThrough.prototype.add = function (acInst, done) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-06-16 07:36:12 +00:00
|
|
|
var definition = this.definition;
|
|
|
|
var modelThrough = definition.modelThrough;
|
|
|
|
var pk1 = definition.keyFrom;
|
2014-06-15 22:53:58 +00:00
|
|
|
|
|
|
|
var data = {};
|
|
|
|
var query = {};
|
2014-07-26 15:20:25 +00:00
|
|
|
|
2014-06-16 07:36:12 +00:00
|
|
|
// The primary key for the target model
|
2014-06-21 18:44:33 +00:00
|
|
|
var pk2 = definition.modelTo.definition.idName();
|
2014-06-16 07:36:12 +00:00
|
|
|
|
2014-07-26 15:20:25 +00:00
|
|
|
var keys = throughKeys(definition);
|
|
|
|
var fk1 = keys[0];
|
|
|
|
var fk2 = keys[1];
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-16 07:36:12 +00:00
|
|
|
query[fk1] = this.modelInstance[pk1];
|
2014-07-15 23:09:54 +00:00
|
|
|
query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst;
|
2014-07-11 13:29:47 +00:00
|
|
|
|
|
|
|
var filter = { where: query };
|
|
|
|
|
|
|
|
definition.applyScope(this.modelInstance, filter);
|
2014-06-16 07:36:12 +00:00
|
|
|
|
|
|
|
data[fk1] = this.modelInstance[pk1];
|
2014-07-15 23:09:54 +00:00
|
|
|
data[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst;
|
2014-07-26 15:20:25 +00:00
|
|
|
|
2014-07-11 22:02:16 +00:00
|
|
|
definition.applyProperties(this.modelInstance, data);
|
2014-06-16 07:36:12 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
// Create an instance of the through model
|
2014-07-11 13:29:47 +00:00
|
|
|
modelThrough.findOrCreate(filter, data, function(err, ac) {
|
2014-06-21 18:44:33 +00:00
|
|
|
if(!err) {
|
|
|
|
if (acInst instanceof definition.modelTo) {
|
|
|
|
self.addToCache(acInst);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
done(err, ac);
|
|
|
|
});
|
2014-06-15 22:53:58 +00:00
|
|
|
};
|
|
|
|
|
2014-07-15 15:50:34 +00:00
|
|
|
/**
|
|
|
|
* Check if the target model instance is related to the 'hasMany' relation
|
|
|
|
* @param {Object|ID} acInst The actual instance or id value
|
|
|
|
*/
|
|
|
|
HasManyThrough.prototype.exists = function (acInst, done) {
|
|
|
|
var definition = this.definition;
|
|
|
|
var modelThrough = definition.modelThrough;
|
|
|
|
var pk1 = definition.keyFrom;
|
|
|
|
|
|
|
|
var query = {};
|
|
|
|
|
|
|
|
// The primary key for the target model
|
|
|
|
var pk2 = definition.modelTo.definition.idName();
|
2014-07-26 15:20:25 +00:00
|
|
|
|
|
|
|
var keys = throughKeys(definition);
|
|
|
|
var fk1 = keys[0];
|
|
|
|
var fk2 = keys[1];
|
2014-08-20 12:03:38 +00:00
|
|
|
|
2014-07-15 15:50:34 +00:00
|
|
|
query[fk1] = this.modelInstance[pk1];
|
2014-07-15 23:09:54 +00:00
|
|
|
query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst;
|
2014-07-26 19:11:25 +00:00
|
|
|
|
|
|
|
var filter = { where: query };
|
|
|
|
|
|
|
|
definition.applyScope(this.modelInstance, filter);
|
|
|
|
|
|
|
|
modelThrough.count(filter.where, function(err, ac) {
|
2014-07-15 15:50:34 +00:00
|
|
|
done(err, ac > 0);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/**
|
|
|
|
* Remove the target model instance from the 'hasMany' relation
|
|
|
|
* @param {Object|ID) acInst The actual instance or id value
|
|
|
|
*/
|
|
|
|
HasManyThrough.prototype.remove = function (acInst, done) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
|
|
|
var definition = this.definition;
|
|
|
|
var modelThrough = definition.modelThrough;
|
|
|
|
var pk1 = definition.keyFrom;
|
2014-06-15 22:53:58 +00:00
|
|
|
|
2014-06-21 18:44:33 +00:00
|
|
|
var query = {};
|
|
|
|
|
|
|
|
// The primary key for the target model
|
|
|
|
var pk2 = definition.modelTo.definition.idName();
|
2014-07-26 15:20:25 +00:00
|
|
|
|
|
|
|
var keys = throughKeys(definition);
|
|
|
|
var fk1 = keys[0];
|
|
|
|
var fk2 = keys[1];
|
2014-06-21 18:44:33 +00:00
|
|
|
|
|
|
|
query[fk1] = this.modelInstance[pk1];
|
2014-07-15 23:09:54 +00:00
|
|
|
query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst;
|
2014-07-11 13:29:47 +00:00
|
|
|
|
|
|
|
var filter = { where: query };
|
|
|
|
|
|
|
|
definition.applyScope(this.modelInstance, filter);
|
2014-07-26 15:20:25 +00:00
|
|
|
|
2014-07-11 13:29:47 +00:00
|
|
|
modelThrough.deleteAll(filter.where, function (err) {
|
2014-06-21 18:44:33 +00:00
|
|
|
if (!err) {
|
|
|
|
self.removeFromCache(query[fk2]);
|
|
|
|
}
|
|
|
|
done(err);
|
|
|
|
});
|
2014-06-15 22:53:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Declare "belongsTo" relation that sets up a one-to-one connection with
|
|
|
|
* another model, such that each instance of the declaring model "belongs to"
|
|
|
|
* one instance of the other model.
|
|
|
|
*
|
|
|
|
* For example, if an application includes users and posts, and each post can
|
|
|
|
* be written by exactly one user. The following code specifies that `Post` has
|
|
|
|
* a reference called `author` to the `User` model via the `userId` property of
|
|
|
|
* `Post` as the foreign key.
|
|
|
|
* ```
|
|
|
|
* Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* This optional parameter default value is false, so the related object will
|
|
|
|
* be loaded from cache if available.
|
|
|
|
*
|
|
|
|
* @param {Class|String} modelTo Model object (or String name of model) to
|
|
|
|
* which you are creating the relationship.
|
|
|
|
* @options {Object} params Configuration parameters; see below.
|
|
|
|
* @property {String} as Name of the property in the referring model that
|
|
|
|
* corresponds to the foreign key field in the related model.
|
|
|
|
* @property {String} foreignKey Name of foreign key property.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
RelationDefinition.belongsTo = function (modelFrom, modelTo, params) {
|
2014-07-28 21:22:45 +00:00
|
|
|
var discriminator, polymorphic;
|
2014-06-15 22:53:58 +00:00
|
|
|
params = params || {};
|
2014-07-26 10:47:55 +00:00
|
|
|
if ('string' === typeof modelTo && !params.polymorphic) {
|
2014-08-09 08:58:03 +00:00
|
|
|
modelTo = lookupModelTo(modelFrom, modelTo, params);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
|
2014-07-28 21:22:45 +00:00
|
|
|
var idName, relationName, fk;
|
2014-07-26 10:47:55 +00:00
|
|
|
if (params.polymorphic) {
|
2014-07-28 08:44:26 +00:00
|
|
|
if (params.polymorphic === true) {
|
2014-07-28 09:12:20 +00:00
|
|
|
// modelTo arg will be the name of the polymorphic relation (string)
|
2014-07-28 21:22:45 +00:00
|
|
|
polymorphic = polymorphicParams(modelTo);
|
2014-07-28 08:44:26 +00:00
|
|
|
} else {
|
2014-07-28 21:22:45 +00:00
|
|
|
polymorphic = polymorphicParams(params.polymorphic);
|
2014-07-28 08:44:26 +00:00
|
|
|
}
|
|
|
|
|
2014-07-26 10:47:55 +00:00
|
|
|
modelTo = null; // will lookup dynamically
|
|
|
|
|
2014-07-28 21:22:45 +00:00
|
|
|
idName = params.idName || 'id';
|
|
|
|
relationName = params.as || polymorphic.as;
|
|
|
|
fk = polymorphic.foreignKey;
|
|
|
|
discriminator = polymorphic.discriminator;
|
2014-07-26 10:47:55 +00:00
|
|
|
|
2014-07-28 08:44:26 +00:00
|
|
|
if (typeof polymorphic.idType === 'string') { // explicit key type
|
|
|
|
modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, { type: polymorphic.idType, index: true });
|
2014-07-26 10:47:55 +00:00
|
|
|
} else { // try to use the same foreign key type as modelFrom
|
|
|
|
modelFrom.dataSource.defineForeignKey(modelFrom.modelName, fk, modelFrom.modelName);
|
|
|
|
}
|
|
|
|
|
2014-07-28 08:18:42 +00:00
|
|
|
modelFrom.dataSource.defineProperty(modelFrom.modelName, discriminator, { type: 'string', index: true });
|
2014-07-26 10:47:55 +00:00
|
|
|
} else {
|
2014-08-22 19:38:28 +00:00
|
|
|
idName = modelTo.dataSource.idName(modelTo.modelName) || 'id';
|
2014-07-28 21:22:45 +00:00
|
|
|
relationName = params.as || i8n.camelize(modelTo.modelName, true);
|
|
|
|
fk = params.foreignKey || relationName + 'Id';
|
2014-07-26 10:47:55 +00:00
|
|
|
|
|
|
|
modelFrom.dataSource.defineForeignKey(modelFrom.modelName, fk, modelTo.modelName);
|
|
|
|
}
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-08-13 09:28:23 +00:00
|
|
|
var definition = modelFrom.relations[relationName] = new RelationDefinition({
|
2014-06-15 22:53:58 +00:00
|
|
|
name: relationName,
|
|
|
|
type: RelationTypes.belongsTo,
|
|
|
|
modelFrom: modelFrom,
|
|
|
|
keyFrom: fk,
|
|
|
|
keyTo: idName,
|
2014-07-21 20:39:06 +00:00
|
|
|
modelTo: modelTo,
|
2014-07-22 20:09:29 +00:00
|
|
|
properties: params.properties,
|
|
|
|
scope: params.scope,
|
2014-08-15 10:55:10 +00:00
|
|
|
options: params.options,
|
|
|
|
polymorphic: polymorphic
|
2014-06-15 22:53:58 +00:00
|
|
|
});
|
2014-07-26 10:47:55 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
// Define a property for the scope so that we have 'this' for the scoped methods
|
|
|
|
Object.defineProperty(modelFrom.prototype, relationName, {
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
get: function() {
|
2014-08-13 09:28:23 +00:00
|
|
|
var relation = new BelongsTo(definition, this);
|
2014-06-16 20:46:17 +00:00
|
|
|
var relationMethod = relation.related.bind(relation);
|
2014-08-20 14:46:54 +00:00
|
|
|
relationMethod.update = relation.update.bind(relation);
|
|
|
|
relationMethod.destroy = relation.destroy.bind(relation);
|
|
|
|
if (!polymorphic) {
|
|
|
|
relationMethod.create = relation.create.bind(relation);
|
|
|
|
relationMethod.build = relation.build.bind(relation);
|
2014-08-13 09:28:23 +00:00
|
|
|
relationMethod._targetClass = definition.modelTo.modelName;
|
2014-07-26 10:47:55 +00:00
|
|
|
}
|
2014-06-15 22:53:58 +00:00
|
|
|
return relationMethod;
|
|
|
|
}
|
|
|
|
});
|
2014-06-16 20:46:17 +00:00
|
|
|
|
2014-06-21 06:54:46 +00:00
|
|
|
// FIXME: [rfeng] Wrap the property into a function for remoting
|
2014-06-16 20:46:17 +00:00
|
|
|
// so that it can be accessed as /api/<model>/<id>/<belongsToRelationName>
|
|
|
|
// For example, /api/orders/1/customer
|
|
|
|
var fn = function() {
|
|
|
|
var f = this[relationName];
|
|
|
|
f.apply(this, arguments);
|
|
|
|
};
|
|
|
|
modelFrom.prototype['__get__' + relationName] = fn;
|
2014-08-13 09:28:23 +00:00
|
|
|
|
|
|
|
return definition;
|
2014-06-15 22:53:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
BelongsTo.prototype.create = function(targetModelData, cb) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-06-15 22:53:58 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
2014-07-23 09:10:44 +00:00
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
var pk = this.definition.keyTo;
|
2014-06-15 22:53:58 +00:00
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
2014-06-27 06:38:04 +00:00
|
|
|
if (typeof targetModelData === 'function' && !cb) {
|
|
|
|
cb = targetModelData;
|
|
|
|
targetModelData = {};
|
|
|
|
}
|
2014-08-15 09:28:25 +00:00
|
|
|
|
2014-07-22 20:09:29 +00:00
|
|
|
this.definition.applyProperties(modelInstance, targetModelData || {});
|
2014-07-26 10:47:55 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
modelTo.create(targetModelData, function(err, targetModel) {
|
|
|
|
if(!err) {
|
|
|
|
modelInstance[fk] = targetModel[pk];
|
2014-08-15 09:28:25 +00:00
|
|
|
modelInstance.save(function(err, inst) {
|
|
|
|
if (cb && err) return cb && cb(err);
|
|
|
|
self.resetCache(targetModel);
|
|
|
|
cb && cb(err, targetModel);
|
|
|
|
});
|
2014-06-15 22:53:58 +00:00
|
|
|
} else {
|
|
|
|
cb && cb(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
BelongsTo.prototype.build = function(targetModelData) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
2014-07-22 20:09:29 +00:00
|
|
|
this.definition.applyProperties(this.modelInstance, targetModelData || {});
|
2014-06-15 22:53:58 +00:00
|
|
|
return new modelTo(targetModelData);
|
|
|
|
};
|
|
|
|
|
2014-08-20 14:46:54 +00:00
|
|
|
BelongsTo.prototype.update = function (targetModelData, cb) {
|
|
|
|
var definition = this.definition;
|
|
|
|
this.fetch(function(err, inst) {
|
|
|
|
if (inst instanceof ModelBaseClass) {
|
|
|
|
inst.updateAttributes(targetModelData, cb);
|
|
|
|
} else {
|
|
|
|
cb(new Error('BelongsTo relation ' + definition.name
|
|
|
|
+ ' is empty'));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
BelongsTo.prototype.destroy = function (cb) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
this.fetch(function(err, targetModel) {
|
|
|
|
if (targetModel instanceof ModelBaseClass) {
|
|
|
|
modelInstance[fk] = null;
|
|
|
|
modelInstance.save(function(err, targetModel) {
|
|
|
|
if (cb && err) return cb && cb(err);
|
|
|
|
cb && cb(err, targetModel);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
cb(new Error('BelongsTo relation ' + definition.name
|
|
|
|
+ ' is empty'));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
/**
|
|
|
|
* Define the method for the belongsTo relation itself
|
|
|
|
* It will support one of the following styles:
|
|
|
|
* - order.customer(refresh, callback): Load the target model instance asynchronously
|
|
|
|
* - order.customer(customer): Synchronous setter of the target model instance
|
|
|
|
* - order.customer(): Synchronous getter of the target model instance
|
|
|
|
*
|
|
|
|
* @param refresh
|
|
|
|
* @param params
|
|
|
|
* @returns {*}
|
|
|
|
*/
|
|
|
|
BelongsTo.prototype.related = function (refresh, params) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-07-26 10:47:55 +00:00
|
|
|
var modelFrom = this.definition.modelFrom;
|
2014-06-15 22:53:58 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var pk = this.definition.keyTo;
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
2014-08-15 10:55:10 +00:00
|
|
|
var discriminator;
|
2014-07-11 22:02:16 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
if (arguments.length === 1) {
|
|
|
|
params = refresh;
|
|
|
|
refresh = false;
|
|
|
|
} else if (arguments.length > 2) {
|
|
|
|
throw new Error('Method can\'t be called with more than two arguments');
|
|
|
|
}
|
2014-07-26 10:47:55 +00:00
|
|
|
|
2014-08-15 10:55:10 +00:00
|
|
|
if (typeof this.definition.polymorphic === 'object') {
|
|
|
|
discriminator = this.definition.polymorphic.discriminator;
|
|
|
|
}
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
var cachedValue;
|
2014-06-21 18:44:33 +00:00
|
|
|
if (!refresh) {
|
|
|
|
cachedValue = self.getCache();
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
if (params instanceof ModelBaseClass) { // acts as setter
|
|
|
|
modelInstance[fk] = params[pk];
|
2014-08-15 10:55:10 +00:00
|
|
|
|
|
|
|
if (discriminator) {
|
|
|
|
modelInstance[discriminator] = params.constructor.modelName;
|
|
|
|
}
|
2014-07-29 08:54:28 +00:00
|
|
|
|
2014-08-15 09:28:25 +00:00
|
|
|
this.definition.applyProperties(modelInstance, params);
|
2014-07-29 08:54:28 +00:00
|
|
|
|
2014-06-21 18:44:33 +00:00
|
|
|
self.resetCache(params);
|
2014-06-15 22:53:58 +00:00
|
|
|
} else if (typeof params === 'function') { // acts as async getter
|
2014-07-26 10:47:55 +00:00
|
|
|
|
2014-08-16 08:23:32 +00:00
|
|
|
if (discriminator) {
|
2014-07-28 08:18:42 +00:00
|
|
|
var modelToName = modelInstance[discriminator];
|
2014-07-26 10:47:55 +00:00
|
|
|
if (typeof modelToName !== 'string') {
|
2014-07-28 08:18:42 +00:00
|
|
|
throw new Error('Polymorphic model not found: `' + discriminator + '` not set');
|
2014-07-26 10:47:55 +00:00
|
|
|
}
|
|
|
|
modelToName = modelToName.toLowerCase();
|
|
|
|
modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName);
|
|
|
|
if (!modelTo) {
|
|
|
|
throw new Error('Polymorphic model not found: `' + modelToName + '`');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
var cb = params;
|
|
|
|
if (cachedValue === undefined) {
|
2014-07-22 20:09:29 +00:00
|
|
|
var query = {where: {}};
|
|
|
|
query.where[pk] = modelInstance[fk];
|
|
|
|
|
2014-08-20 14:46:54 +00:00
|
|
|
if (query.where[pk] === undefined
|
|
|
|
|| query.where[pk] === null) {
|
2014-07-27 07:38:50 +00:00
|
|
|
// Foreign key is undefined
|
|
|
|
return process.nextTick(cb);
|
|
|
|
}
|
|
|
|
|
2014-07-22 20:09:29 +00:00
|
|
|
this.definition.applyScope(modelInstance, query);
|
|
|
|
|
|
|
|
modelTo.findOne(query, function (err, inst) {
|
2014-06-15 22:53:58 +00:00
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
if (!inst) {
|
|
|
|
return cb(null, null);
|
|
|
|
}
|
|
|
|
// Check if the foreign key matches the primary key
|
2014-07-23 09:10:44 +00:00
|
|
|
if (inst[pk] && modelInstance[fk]
|
|
|
|
&& inst[pk].toString() === modelInstance[fk].toString()) {
|
2014-06-21 18:44:33 +00:00
|
|
|
self.resetCache(inst);
|
2014-06-15 22:53:58 +00:00
|
|
|
cb(null, inst);
|
|
|
|
} else {
|
2014-07-15 15:50:34 +00:00
|
|
|
err = new Error('Key mismatch: ' + self.definition.modelFrom.modelName + '.' + fk
|
|
|
|
+ ': ' + modelInstance[fk]
|
|
|
|
+ ', ' + modelTo.modelName + '.' + pk + ': ' + inst[pk]);
|
|
|
|
err.statusCode = 400;
|
|
|
|
cb(err);
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
return modelInstance[fk];
|
|
|
|
} else {
|
|
|
|
cb(null, cachedValue);
|
|
|
|
return cachedValue;
|
|
|
|
}
|
|
|
|
} else if (params === undefined) { // acts as sync getter
|
2014-06-27 06:38:04 +00:00
|
|
|
return cachedValue;
|
2014-06-15 22:53:58 +00:00
|
|
|
} else { // setter
|
|
|
|
modelInstance[fk] = params;
|
2014-06-21 18:44:33 +00:00
|
|
|
self.resetCache();
|
2014-06-15 22:53:58 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
2014-06-19 18:13:24 +00:00
|
|
|
* A hasAndBelongsToMany relation creates a direct many-to-many connection with
|
|
|
|
* another model, with no intervening model. For example, if your application
|
|
|
|
* includes users and groups, with each group having many users and each user
|
|
|
|
* appearing in many groups, you could declare the models this way:
|
2014-06-15 22:53:58 +00:00
|
|
|
* ```
|
|
|
|
* User.hasAndBelongsToMany('groups', {model: Group, foreignKey: 'groupId'});
|
|
|
|
* ```
|
|
|
|
*
|
2014-06-19 18:13:24 +00:00
|
|
|
* @param {String|Object} modelTo Model object (or String name of model) to
|
|
|
|
* which you are creating the relationship.
|
2014-06-15 22:53:58 +00:00
|
|
|
* @options {Object} params Configuration parameters; see below.
|
2014-06-19 18:13:24 +00:00
|
|
|
* @property {String} as Name of the property in the referring model that
|
|
|
|
* corresponds to the foreign key field in the related model.
|
2014-06-15 22:53:58 +00:00
|
|
|
* @property {String} foreignKey Property name of foreign key field.
|
|
|
|
* @property {Object} model Model object
|
|
|
|
*/
|
|
|
|
RelationDefinition.hasAndBelongsToMany = function hasAndBelongsToMany(modelFrom, modelTo, params) {
|
|
|
|
params = params || {};
|
2014-08-09 08:58:03 +00:00
|
|
|
modelTo = lookupModelTo(modelFrom, modelTo, params, true);
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
var models = modelFrom.dataSource.modelBuilder.models;
|
2014-07-28 09:12:20 +00:00
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
if (!params.through) {
|
2014-07-28 09:12:20 +00:00
|
|
|
if (params.polymorphic) throw new Error('Polymorphic relations need a through model');
|
2014-06-15 22:53:58 +00:00
|
|
|
var name1 = modelFrom.modelName + modelTo.modelName;
|
|
|
|
var name2 = modelTo.modelName + modelFrom.modelName;
|
|
|
|
params.through = lookupModel(models, name1) || lookupModel(models, name2) ||
|
|
|
|
modelFrom.dataSource.define(name1);
|
|
|
|
}
|
2014-07-26 12:54:54 +00:00
|
|
|
|
|
|
|
var options = {as: params.as, through: params.through};
|
2014-07-26 19:32:24 +00:00
|
|
|
options.properties = params.properties;
|
|
|
|
options.scope = params.scope;
|
2014-07-26 12:54:54 +00:00
|
|
|
|
2014-07-28 09:12:20 +00:00
|
|
|
if (params.polymorphic) {
|
|
|
|
var polymorphic = polymorphicParams(params.polymorphic);
|
|
|
|
options.polymorphic = polymorphic; // pass through
|
|
|
|
var accessor = params.through.prototype[polymorphic.as];
|
2014-07-26 12:54:54 +00:00
|
|
|
if (typeof accessor !== 'function') { // declare once
|
2014-07-28 09:12:20 +00:00
|
|
|
// use the name of the polymorphic rel, not modelTo
|
|
|
|
params.through.belongsTo(polymorphic.as, { polymorphic: true });
|
2014-07-26 12:54:54 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
params.through.belongsTo(modelFrom);
|
|
|
|
}
|
|
|
|
|
2014-06-15 22:53:58 +00:00
|
|
|
params.through.belongsTo(modelTo);
|
2014-07-26 13:23:40 +00:00
|
|
|
|
2014-08-13 09:28:23 +00:00
|
|
|
return this.hasMany(modelFrom, modelTo, options);
|
2014-06-15 22:53:58 +00:00
|
|
|
};
|
2014-06-16 08:17:37 +00:00
|
|
|
|
|
|
|
/**
|
2014-06-19 18:13:24 +00:00
|
|
|
* A HasOne relation creates a one-to-one connection from modelFrom to modelTo.
|
|
|
|
* This relation indicates that each instance of a model contains or possesses
|
|
|
|
* one instance of another model. For example, each supplier in your application
|
|
|
|
* has only one account.
|
|
|
|
*
|
|
|
|
* @param {Function} modelFrom The declaring model class
|
|
|
|
* @param {String|Function} modelTo Model object (or String name of model) to
|
|
|
|
* which you are creating the relationship.
|
|
|
|
* @options {Object} params Configuration parameters; see below.
|
|
|
|
* @property {String} as Name of the property in the referring model that
|
|
|
|
* corresponds to the foreign key field in the related model.
|
|
|
|
* @property {String} foreignKey Property name of foreign key field.
|
|
|
|
* @property {Object} model Model object
|
2014-06-16 08:17:37 +00:00
|
|
|
*/
|
|
|
|
RelationDefinition.hasOne = function (modelFrom, modelTo, params) {
|
|
|
|
params = params || {};
|
2014-08-09 08:58:03 +00:00
|
|
|
modelTo = lookupModelTo(modelFrom, modelTo, params);
|
2014-06-16 08:17:37 +00:00
|
|
|
|
2014-08-22 19:38:28 +00:00
|
|
|
var pk = modelTo.dataSource.idName(modelTo.modelName) || 'id';
|
2014-06-16 08:17:37 +00:00
|
|
|
var relationName = params.as || i8n.camelize(modelTo.modelName, true);
|
|
|
|
|
|
|
|
var fk = params.foreignKey || i8n.camelize(modelFrom.modelName + '_id', true);
|
2014-08-15 10:55:10 +00:00
|
|
|
var discriminator, polymorphic;
|
2014-07-26 13:20:46 +00:00
|
|
|
|
2014-07-28 09:12:20 +00:00
|
|
|
if (params.polymorphic) {
|
2014-08-15 10:55:10 +00:00
|
|
|
polymorphic = polymorphicParams(params.polymorphic);
|
2014-07-28 09:12:20 +00:00
|
|
|
fk = polymorphic.foreignKey;
|
|
|
|
discriminator = polymorphic.discriminator;
|
2014-07-26 13:20:46 +00:00
|
|
|
if (!params.through) {
|
2014-07-28 08:18:42 +00:00
|
|
|
modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, { type: 'string', index: true });
|
2014-07-26 13:20:46 +00:00
|
|
|
}
|
|
|
|
}
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-08-13 09:28:23 +00:00
|
|
|
var definition = modelFrom.relations[relationName] = new RelationDefinition({
|
2014-06-16 08:17:37 +00:00
|
|
|
name: relationName,
|
|
|
|
type: RelationTypes.hasOne,
|
|
|
|
modelFrom: modelFrom,
|
|
|
|
keyFrom: pk,
|
|
|
|
keyTo: fk,
|
2014-07-11 13:29:47 +00:00
|
|
|
modelTo: modelTo,
|
2014-07-21 20:39:06 +00:00
|
|
|
properties: params.properties,
|
2014-08-15 10:55:10 +00:00
|
|
|
options: params.options,
|
|
|
|
polymorphic: polymorphic
|
2014-06-16 08:17:37 +00:00
|
|
|
});
|
|
|
|
|
2014-08-22 19:38:28 +00:00
|
|
|
modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName);
|
2014-06-16 08:17:37 +00:00
|
|
|
|
|
|
|
// Define a property for the scope so that we have 'this' for the scoped methods
|
|
|
|
Object.defineProperty(modelFrom.prototype, relationName, {
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
get: function() {
|
2014-08-13 09:28:23 +00:00
|
|
|
var relation = new HasOne(definition, this);
|
2014-06-16 08:17:37 +00:00
|
|
|
var relationMethod = relation.related.bind(relation)
|
|
|
|
relationMethod.create = relation.create.bind(relation);
|
|
|
|
relationMethod.build = relation.build.bind(relation);
|
2014-08-20 13:54:47 +00:00
|
|
|
relationMethod.update = relation.update.bind(relation);
|
|
|
|
relationMethod.destroy = relation.destroy.bind(relation);
|
2014-08-13 09:28:23 +00:00
|
|
|
relationMethod._targetClass = definition.modelTo.modelName;
|
2014-06-16 08:17:37 +00:00
|
|
|
return relationMethod;
|
|
|
|
}
|
|
|
|
});
|
2014-08-01 09:24:41 +00:00
|
|
|
|
|
|
|
// FIXME: [rfeng] Wrap the property into a function for remoting
|
|
|
|
// so that it can be accessed as /api/<model>/<id>/<hasOneRelationName>
|
|
|
|
// For example, /api/orders/1/customer
|
|
|
|
var fn = function() {
|
|
|
|
var f = this[relationName];
|
|
|
|
f.apply(this, arguments);
|
|
|
|
};
|
|
|
|
modelFrom.prototype['__get__' + relationName] = fn;
|
2014-08-13 09:28:23 +00:00
|
|
|
|
|
|
|
return definition;
|
2014-06-16 08:17:37 +00:00
|
|
|
};
|
|
|
|
|
2014-06-19 18:13:24 +00:00
|
|
|
/**
|
|
|
|
* Create a target model instance
|
|
|
|
* @param {Object} targetModelData The target model data
|
|
|
|
* @callback {Function} [cb] Callback function
|
|
|
|
* @param {String|Object} err Error string or object
|
|
|
|
* @param {Object} The newly created target model instance
|
|
|
|
*/
|
2014-06-27 06:38:04 +00:00
|
|
|
HasOne.prototype.create = function (targetModelData, cb) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-06-16 08:17:37 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var fk = this.definition.keyTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
2014-06-27 06:38:04 +00:00
|
|
|
if (typeof targetModelData === 'function' && !cb) {
|
|
|
|
cb = targetModelData;
|
|
|
|
targetModelData = {};
|
|
|
|
}
|
2014-06-16 08:17:37 +00:00
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
targetModelData[fk] = modelInstance[pk];
|
2014-06-27 06:38:04 +00:00
|
|
|
var query = {where: {}};
|
2014-07-11 13:29:47 +00:00
|
|
|
query.where[fk] = targetModelData[fk];
|
|
|
|
|
|
|
|
this.definition.applyScope(modelInstance, query);
|
2014-07-11 22:02:16 +00:00
|
|
|
this.definition.applyProperties(modelInstance, targetModelData);
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-27 06:38:04 +00:00
|
|
|
modelTo.findOne(query, function(err, result) {
|
|
|
|
if(err) {
|
|
|
|
cb(err);
|
|
|
|
} else if(result) {
|
|
|
|
cb(new Error('HasOne relation cannot create more than one instance of '
|
|
|
|
+ modelTo.modelName));
|
|
|
|
} else {
|
|
|
|
modelTo.create(targetModelData, function (err, targetModel) {
|
|
|
|
if (!err) {
|
|
|
|
// Refresh the cache
|
|
|
|
self.resetCache(targetModel);
|
|
|
|
cb && cb(err, targetModel);
|
|
|
|
} else {
|
|
|
|
cb && cb(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-08-20 13:54:47 +00:00
|
|
|
HasOne.prototype.update = function (targetModelData, cb) {
|
|
|
|
var definition = this.definition;
|
2014-08-20 14:46:54 +00:00
|
|
|
this.fetch(function(err, targetModel) {
|
|
|
|
if (targetModel instanceof ModelBaseClass) {
|
|
|
|
targetModel.updateAttributes(targetModelData, cb);
|
2014-08-20 13:54:47 +00:00
|
|
|
} else {
|
|
|
|
cb(new Error('HasOne relation ' + definition.name
|
|
|
|
+ ' is empty'));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
HasOne.prototype.destroy = function (cb) {
|
2014-08-20 14:46:54 +00:00
|
|
|
this.fetch(function(err, targetModel) {
|
|
|
|
if (targetModel instanceof ModelBaseClass) {
|
|
|
|
targetModel.destroy(cb);
|
2014-08-20 13:58:45 +00:00
|
|
|
} else {
|
|
|
|
cb(new Error('HasOne relation ' + definition.name
|
|
|
|
+ ' is empty'));
|
|
|
|
}
|
|
|
|
});
|
2014-08-20 13:54:47 +00:00
|
|
|
};
|
|
|
|
|
2014-06-27 06:38:04 +00:00
|
|
|
/**
|
|
|
|
* Create a target model instance
|
|
|
|
* @param {Object} targetModelData The target model data
|
|
|
|
* @callback {Function} [cb] Callback function
|
|
|
|
* @param {String|Object} err Error string or object
|
|
|
|
* @param {Object} The newly created target model instance
|
|
|
|
*/
|
|
|
|
HasMany.prototype.create = function (targetModelData, cb) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-06-16 08:17:37 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var fk = this.definition.keyTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-27 06:38:04 +00:00
|
|
|
if (typeof targetModelData === 'function' && !cb) {
|
|
|
|
cb = targetModelData;
|
|
|
|
targetModelData = {};
|
|
|
|
}
|
2014-06-16 08:17:37 +00:00
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
targetModelData[fk] = modelInstance[pk];
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-07-11 22:02:16 +00:00
|
|
|
this.definition.applyProperties(modelInstance, targetModelData);
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-16 08:17:37 +00:00
|
|
|
modelTo.create(targetModelData, function(err, targetModel) {
|
|
|
|
if(!err) {
|
2014-06-21 18:44:33 +00:00
|
|
|
// Refresh the cache
|
2014-06-27 06:38:04 +00:00
|
|
|
self.addToCache(targetModel);
|
2014-06-16 08:17:37 +00:00
|
|
|
cb && cb(err, targetModel);
|
|
|
|
} else {
|
|
|
|
cb && cb(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
2014-06-19 18:13:24 +00:00
|
|
|
/**
|
|
|
|
* Build a target model instance
|
|
|
|
* @param {Object} targetModelData The target model data
|
|
|
|
* @returns {Object} The newly built target model instance
|
|
|
|
*/
|
2014-06-27 06:38:04 +00:00
|
|
|
HasMany.prototype.build = HasOne.prototype.build = function(targetModelData) {
|
2014-06-16 08:17:37 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
|
|
|
var fk = this.definition.keyTo;
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-16 08:17:37 +00:00
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
targetModelData[fk] = this.modelInstance[pk];
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-07-11 22:02:16 +00:00
|
|
|
this.definition.applyProperties(this.modelInstance, targetModelData);
|
2014-07-11 13:29:47 +00:00
|
|
|
|
2014-06-16 08:17:37 +00:00
|
|
|
return new modelTo(targetModelData);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Define the method for the hasOne relation itself
|
|
|
|
* It will support one of the following styles:
|
|
|
|
* - order.customer(refresh, callback): Load the target model instance asynchronously
|
|
|
|
* - order.customer(customer): Synchronous setter of the target model instance
|
|
|
|
* - order.customer(): Synchronous getter of the target model instance
|
|
|
|
*
|
2014-06-19 18:13:24 +00:00
|
|
|
* @param {Boolean} refresh Reload from the data source
|
|
|
|
* @param {Object|Function} params Query parameters
|
|
|
|
* @returns {Object}
|
2014-06-16 08:17:37 +00:00
|
|
|
*/
|
|
|
|
HasOne.prototype.related = function (refresh, params) {
|
2014-06-21 18:44:33 +00:00
|
|
|
var self = this;
|
2014-06-16 08:17:37 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var fk = this.definition.keyTo;
|
|
|
|
var pk = this.definition.keyFrom;
|
2014-07-11 13:29:47 +00:00
|
|
|
var definition = this.definition;
|
2014-06-16 08:17:37 +00:00
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
if (arguments.length === 1) {
|
|
|
|
params = refresh;
|
|
|
|
refresh = false;
|
|
|
|
} else if (arguments.length > 2) {
|
|
|
|
throw new Error('Method can\'t be called with more than two arguments');
|
|
|
|
}
|
|
|
|
|
|
|
|
var cachedValue;
|
2014-06-21 18:44:33 +00:00
|
|
|
if (!refresh) {
|
|
|
|
cachedValue = self.getCache();
|
2014-06-16 08:17:37 +00:00
|
|
|
}
|
|
|
|
if (params instanceof ModelBaseClass) { // acts as setter
|
|
|
|
params[fk] = modelInstance[pk];
|
2014-06-21 18:44:33 +00:00
|
|
|
self.resetCache(params);
|
2014-06-16 08:17:37 +00:00
|
|
|
} else if (typeof params === 'function') { // acts as async getter
|
|
|
|
var cb = params;
|
|
|
|
if (cachedValue === undefined) {
|
|
|
|
var query = {where: {}};
|
|
|
|
query.where[fk] = modelInstance[pk];
|
2014-07-11 13:29:47 +00:00
|
|
|
definition.applyScope(modelInstance, query);
|
2014-06-16 08:17:37 +00:00
|
|
|
modelTo.findOne(query, function (err, inst) {
|
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
if (!inst) {
|
|
|
|
return cb(null, null);
|
|
|
|
}
|
|
|
|
// Check if the foreign key matches the primary key
|
2014-07-23 09:10:44 +00:00
|
|
|
if (inst[fk] && modelInstance[pk]
|
|
|
|
&& inst[fk].toString() === modelInstance[pk].toString()) {
|
2014-06-21 18:44:33 +00:00
|
|
|
self.resetCache(inst);
|
2014-06-16 08:17:37 +00:00
|
|
|
cb(null, inst);
|
|
|
|
} else {
|
2014-07-15 15:50:34 +00:00
|
|
|
err = new Error('Key mismatch: ' + self.definition.modelFrom.modelName + '.' + pk
|
|
|
|
+ ': ' + modelInstance[pk]
|
|
|
|
+ ', ' + modelTo.modelName + '.' + fk + ': ' + inst[fk]);
|
|
|
|
err.statusCode = 400;
|
|
|
|
cb(err);
|
2014-06-16 08:17:37 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
return modelInstance[pk];
|
|
|
|
} else {
|
|
|
|
cb(null, cachedValue);
|
|
|
|
return cachedValue;
|
|
|
|
}
|
|
|
|
} else if (params === undefined) { // acts as sync getter
|
2014-06-27 06:38:04 +00:00
|
|
|
return cachedValue;
|
2014-06-16 08:17:37 +00:00
|
|
|
} else { // setter
|
|
|
|
params[fk] = modelInstance[pk];
|
2014-06-21 18:44:33 +00:00
|
|
|
self.resetCache();
|
2014-06-16 08:17:37 +00:00
|
|
|
}
|
|
|
|
};
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-08-19 20:10:35 +00:00
|
|
|
RelationDefinition.embedsOne = function (modelFrom, modelTo, params) {
|
|
|
|
params = params || {};
|
|
|
|
modelTo = lookupModelTo(modelFrom, modelTo, params);
|
|
|
|
|
|
|
|
var thisClassName = modelFrom.modelName;
|
|
|
|
var relationName = params.as || (i8n.camelize(modelTo.modelName, true) + 'Item');
|
|
|
|
var propertyName = params.property || i8n.camelize(modelTo.modelName, true);
|
|
|
|
var idName = modelTo.dataSource.idName(modelTo.modelName) || 'id';
|
|
|
|
|
|
|
|
if (relationName === propertyName) {
|
|
|
|
propertyName = '_' + propertyName;
|
|
|
|
debug('EmbedsOne property cannot be equal to relation name: ' +
|
|
|
|
'forcing property %s for relation %s', propertyName, relationName);
|
|
|
|
}
|
|
|
|
|
|
|
|
var definition = modelFrom.relations[relationName] = new RelationDefinition({
|
|
|
|
name: relationName,
|
|
|
|
type: RelationTypes.embedsOne,
|
|
|
|
modelFrom: modelFrom,
|
|
|
|
keyFrom: propertyName,
|
|
|
|
keyTo: idName,
|
|
|
|
modelTo: modelTo,
|
|
|
|
multiple: false,
|
|
|
|
properties: params.properties,
|
|
|
|
scope: params.scope,
|
|
|
|
options: params.options,
|
|
|
|
embed: true
|
|
|
|
});
|
|
|
|
|
|
|
|
var opts = { type: modelTo };
|
|
|
|
|
|
|
|
if (params.default === true) {
|
|
|
|
opts.default = function() { return new modelTo(); };
|
|
|
|
} else if (typeof params.default === 'object') {
|
|
|
|
opts.default = (function(def) {
|
2014-08-20 21:22:47 +00:00
|
|
|
return function() {
|
|
|
|
return new modelTo(def);
|
|
|
|
};
|
2014-08-19 20:10:35 +00:00
|
|
|
}(params.default));
|
|
|
|
}
|
|
|
|
|
|
|
|
modelFrom.dataSource.defineProperty(modelFrom.modelName, propertyName, opts);
|
|
|
|
|
|
|
|
// validate the embedded instance
|
2014-08-19 20:15:30 +00:00
|
|
|
if (definition.options.validate !== false) {
|
2014-08-19 20:10:35 +00:00
|
|
|
modelFrom.validate(relationName, function(err) {
|
|
|
|
var inst = this[propertyName];
|
|
|
|
if (inst instanceof modelTo) {
|
|
|
|
if (!inst.isValid()) {
|
|
|
|
var first = Object.keys(inst.errors)[0];
|
|
|
|
var msg = 'is invalid: `' + first + '` ' + inst.errors[first];
|
|
|
|
this.errors.add(relationName, msg, 'invalid');
|
|
|
|
err(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Define a property for the scope so that we have 'this' for the scoped methods
|
|
|
|
Object.defineProperty(modelFrom.prototype, relationName, {
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
get: function() {
|
|
|
|
var relation = new EmbedsOne(definition, this);
|
|
|
|
var relationMethod = relation.related.bind(relation)
|
|
|
|
relationMethod.create = relation.create.bind(relation);
|
|
|
|
relationMethod.build = relation.build.bind(relation);
|
2014-08-20 13:37:40 +00:00
|
|
|
relationMethod.update = relation.update.bind(relation);
|
2014-08-19 20:10:35 +00:00
|
|
|
relationMethod.destroy = relation.destroy.bind(relation);
|
|
|
|
relationMethod._targetClass = definition.modelTo.modelName;
|
|
|
|
return relationMethod;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// FIXME: [rfeng] Wrap the property into a function for remoting
|
|
|
|
// so that it can be accessed as /api/<model>/<id>/<embedsOneRelationName>
|
|
|
|
// For example, /api/orders/1/customer
|
|
|
|
var fn = function() {
|
|
|
|
var f = this[relationName];
|
|
|
|
f.apply(this, arguments);
|
|
|
|
};
|
|
|
|
modelFrom.prototype['__get__' + relationName] = fn;
|
|
|
|
|
|
|
|
return definition;
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsOne.prototype.related = function (refresh, params) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
var propertyName = this.definition.keyFrom;
|
|
|
|
|
|
|
|
if (arguments.length === 1) {
|
|
|
|
params = refresh;
|
|
|
|
refresh = false;
|
|
|
|
} else if (arguments.length > 2) {
|
|
|
|
throw new Error('Method can\'t be called with more than two arguments');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (params instanceof ModelBaseClass) { // acts as setter
|
|
|
|
if (params instanceof modelTo) {
|
|
|
|
this.definition.applyProperties(modelInstance, params);
|
|
|
|
modelInstance.setAttribute(propertyName, params);
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var embeddedInstance = modelInstance[propertyName];
|
|
|
|
if (typeof params === 'function') { // acts as async getter
|
|
|
|
var cb = params;
|
|
|
|
process.nextTick(function() {
|
|
|
|
cb(null, embeddedInstance);
|
|
|
|
});
|
|
|
|
} else if (params === undefined) { // acts as sync getter
|
|
|
|
return embeddedInstance;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsOne.prototype.create = function (targetModelData, cb) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var propertyName = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
if (typeof targetModelData === 'function' && !cb) {
|
|
|
|
cb = targetModelData;
|
|
|
|
targetModelData = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
|
|
|
|
var inst = this.build(targetModelData);
|
|
|
|
|
|
|
|
var err = inst.isValid() ? null : new ValidationError(inst);
|
|
|
|
|
|
|
|
if (err) {
|
|
|
|
return process.nextTick(function() {
|
|
|
|
cb(err);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
modelInstance.updateAttribute(propertyName,
|
|
|
|
inst, function(err) {
|
|
|
|
cb(err, err ? null : inst);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsOne.prototype.build = function (targetModelData) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
2014-08-20 13:37:40 +00:00
|
|
|
var propertyName = this.definition.keyFrom;
|
2014-08-19 20:10:35 +00:00
|
|
|
|
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
|
|
|
|
this.definition.applyProperties(modelInstance, targetModelData);
|
|
|
|
|
2014-08-20 13:37:40 +00:00
|
|
|
var embeddedInstance = new modelTo(targetModelData);
|
|
|
|
modelInstance[propertyName] = embeddedInstance;
|
|
|
|
|
|
|
|
return embeddedInstance;
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsOne.prototype.update = function (targetModelData, cb) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
var propertyName = this.definition.keyFrom;
|
|
|
|
|
|
|
|
var isInst = targetModelData instanceof ModelBaseClass;
|
|
|
|
var data = isInst ? targetModelData.toObject() : targetModelData;
|
|
|
|
|
|
|
|
var embeddedInstance = modelInstance[propertyName];
|
|
|
|
if (embeddedInstance instanceof modelTo) {
|
|
|
|
embeddedInstance.setAttributes(data);
|
|
|
|
if (typeof cb === 'function') {
|
|
|
|
modelInstance.save(function(err, inst) {
|
|
|
|
cb(err, inst ? inst[propertyName] : embeddedInstance);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} else if (!embeddedInstance && cb) {
|
|
|
|
this.create(data, db);
|
|
|
|
} else if (!embeddedInstance) {
|
|
|
|
this.build(data);
|
|
|
|
}
|
2014-08-19 20:10:35 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsOne.prototype.destroy = function (cb) {
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
var propertyName = this.definition.keyFrom;
|
|
|
|
modelInstance.unsetAttribute(propertyName, true);
|
2014-08-20 21:22:47 +00:00
|
|
|
modelInstance.save(function (err, result) {
|
|
|
|
cb && cb(err, result);
|
|
|
|
});
|
2014-08-19 20:10:35 +00:00
|
|
|
};
|
|
|
|
|
2014-07-29 13:01:47 +00:00
|
|
|
RelationDefinition.embedsMany = function embedsMany(modelFrom, modelTo, params) {
|
2014-07-27 14:30:45 +00:00
|
|
|
params = params || {};
|
2014-08-09 08:58:03 +00:00
|
|
|
modelTo = lookupModelTo(modelFrom, modelTo, params, true);
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-08-09 08:58:03 +00:00
|
|
|
var thisClassName = modelFrom.modelName;
|
2014-08-11 13:33:41 +00:00
|
|
|
var relationName = params.as || (i8n.camelize(modelTo.modelName, true) + 'List');
|
|
|
|
var propertyName = params.property || i8n.camelize(modelTo.pluralModelName, true);
|
|
|
|
var idName = modelTo.dataSource.idName(modelTo.modelName) || 'id';
|
|
|
|
|
|
|
|
if (relationName === propertyName) {
|
|
|
|
propertyName = '_' + propertyName;
|
|
|
|
debug('EmbedsMany property cannot be equal to relation name: ' +
|
|
|
|
'forcing property %s for relation %s', propertyName, relationName);
|
|
|
|
}
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-08-11 13:33:41 +00:00
|
|
|
var definition = modelFrom.relations[relationName] = new RelationDefinition({
|
2014-07-27 14:30:45 +00:00
|
|
|
name: relationName,
|
|
|
|
type: RelationTypes.embedsMany,
|
|
|
|
modelFrom: modelFrom,
|
2014-08-11 13:33:41 +00:00
|
|
|
keyFrom: propertyName,
|
|
|
|
keyTo: idName,
|
2014-07-27 14:30:45 +00:00
|
|
|
modelTo: modelTo,
|
|
|
|
multiple: true,
|
|
|
|
properties: params.properties,
|
|
|
|
scope: params.scope,
|
|
|
|
options: params.options,
|
|
|
|
embed: true
|
|
|
|
});
|
|
|
|
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.dataSource.defineProperty(modelFrom.modelName, propertyName, {
|
2014-07-27 14:30:45 +00:00
|
|
|
type: [modelTo], default: function() { return []; }
|
|
|
|
});
|
|
|
|
|
2014-08-30 09:43:36 +00:00
|
|
|
if (typeof modelTo.dataSource.connector.generateId !== 'function') {
|
|
|
|
modelTo.validatesPresenceOf(idName); // unique id is required
|
|
|
|
}
|
2014-07-29 11:57:49 +00:00
|
|
|
|
|
|
|
if (!params.polymorphic) {
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.validate(propertyName, function(err) {
|
|
|
|
var embeddedList = this[propertyName] || [];
|
2014-07-29 11:57:49 +00:00
|
|
|
var ids = embeddedList.map(function(m) { return m[idName]; });
|
|
|
|
var uniqueIds = ids.filter(function(id, pos) {
|
|
|
|
return ids.indexOf(id) === pos;
|
|
|
|
});
|
|
|
|
if (ids.length !== uniqueIds.length) {
|
2014-08-29 19:30:42 +00:00
|
|
|
this.errors.add(propertyName, 'contains duplicate `' + idName + '`', 'uniqueness');
|
2014-07-29 11:57:49 +00:00
|
|
|
err(false);
|
|
|
|
}
|
|
|
|
}, { code: 'uniqueness' })
|
|
|
|
}
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-07-27 14:54:01 +00:00
|
|
|
// validate all embedded items
|
2014-08-19 20:15:30 +00:00
|
|
|
if (definition.options.validate !== false) {
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.validate(propertyName, function(err) {
|
2014-07-30 13:01:55 +00:00
|
|
|
var self = this;
|
2014-08-11 13:33:41 +00:00
|
|
|
var embeddedList = this[propertyName] || [];
|
2014-07-27 14:54:01 +00:00
|
|
|
var hasErrors = false;
|
|
|
|
embeddedList.forEach(function(item) {
|
|
|
|
if (item instanceof modelTo) {
|
|
|
|
if (!item.isValid()) {
|
|
|
|
hasErrors = true;
|
2014-07-27 14:56:30 +00:00
|
|
|
var id = item[idName] || '(blank)';
|
2014-07-27 14:54:01 +00:00
|
|
|
var first = Object.keys(item.errors)[0];
|
2014-07-27 14:56:30 +00:00
|
|
|
var msg = 'contains invalid item: `' + id + '`';
|
2014-08-19 20:10:35 +00:00
|
|
|
msg += ' (`' + first + '` ' + item.errors[first] + ')';
|
2014-08-11 13:33:41 +00:00
|
|
|
self.errors.add(propertyName, msg, 'invalid');
|
2014-07-27 14:54:01 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
hasErrors = true;
|
2014-08-29 19:30:42 +00:00
|
|
|
self.errors.add(propertyName, 'contains invalid item', 'invalid');
|
2014-07-27 14:54:01 +00:00
|
|
|
}
|
2014-07-30 13:01:55 +00:00
|
|
|
});
|
2014-07-27 14:54:01 +00:00
|
|
|
if (hasErrors) err(false);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2014-07-27 14:30:45 +00:00
|
|
|
var scopeMethods = {
|
|
|
|
findById: scopeMethod(definition, 'findById'),
|
|
|
|
destroy: scopeMethod(definition, 'destroyById'),
|
|
|
|
updateById: scopeMethod(definition, 'updateById'),
|
2014-07-29 08:51:33 +00:00
|
|
|
exists: scopeMethod(definition, 'exists'),
|
2014-07-29 15:43:30 +00:00
|
|
|
add: scopeMethod(definition, 'add'),
|
|
|
|
remove: scopeMethod(definition, 'remove'),
|
2014-07-29 08:51:33 +00:00
|
|
|
get: scopeMethod(definition, 'get'),
|
|
|
|
set: scopeMethod(definition, 'set'),
|
2014-07-29 15:43:30 +00:00
|
|
|
unset: scopeMethod(definition, 'unset'),
|
2014-07-29 08:51:33 +00:00
|
|
|
at: scopeMethod(definition, 'at')
|
2014-07-27 14:30:45 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
var findByIdFunc = scopeMethods.findById;
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.prototype['__findById__' + relationName] = findByIdFunc;
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var destroyByIdFunc = scopeMethods.destroy;
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc;
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var updateByIdFunc = scopeMethods.updateById;
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc;
|
2014-07-29 15:43:30 +00:00
|
|
|
|
|
|
|
var addFunc = scopeMethods.add;
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.prototype['__link__' + relationName] = addFunc;
|
2014-07-29 15:43:30 +00:00
|
|
|
|
|
|
|
var removeFunc = scopeMethods.remove;
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.prototype['__unlink__' + relationName] = removeFunc;
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
scopeMethods.create = scopeMethod(definition, 'create');
|
|
|
|
scopeMethods.build = scopeMethod(definition, 'build');
|
|
|
|
|
2014-07-29 20:59:44 +00:00
|
|
|
scopeMethods.related = scopeMethod(definition, 'related'); // bound to definition
|
|
|
|
|
2014-07-30 14:46:05 +00:00
|
|
|
var customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods);
|
|
|
|
|
|
|
|
for (var i = 0; i < customMethods.length; i++) {
|
|
|
|
var methodName = customMethods[i];
|
|
|
|
var method = scopeMethods[methodName];
|
|
|
|
if (typeof method === 'function' && method.shared === true) {
|
2014-08-11 13:33:41 +00:00
|
|
|
modelFrom.prototype['__' + methodName + '__' + relationName] = method;
|
2014-07-30 14:46:05 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-07-27 14:30:45 +00:00
|
|
|
// Mix the property and scoped methods into the prototype class
|
2014-08-11 13:33:41 +00:00
|
|
|
var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function () {
|
2014-07-27 14:30:45 +00:00
|
|
|
return {};
|
2014-08-08 16:25:49 +00:00
|
|
|
}, scopeMethods, definition.options);
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-07-29 20:59:44 +00:00
|
|
|
scopeDefinition.related = scopeMethods.related;
|
2014-08-13 09:28:23 +00:00
|
|
|
|
|
|
|
return definition;
|
2014-07-27 14:30:45 +00:00
|
|
|
};
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
EmbedsMany.prototype.prepareEmbeddedInstance = function(inst) {
|
|
|
|
if (inst && inst.triggerParent !== 'function') {
|
|
|
|
var self = this;
|
|
|
|
var propertyName = this.definition.keyFrom;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
inst.triggerParent = function(actionName, callback) {
|
|
|
|
if (actionName === 'save' || actionName === 'destroy') {
|
|
|
|
var embeddedList = self.embeddedList();
|
|
|
|
if (actionName === 'destroy') {
|
|
|
|
var index = embeddedList.indexOf(inst);
|
|
|
|
if (index > -1) embeddedList.splice(index, 1);
|
|
|
|
}
|
|
|
|
modelInstance.updateAttribute(propertyName,
|
|
|
|
embeddedList, function(err, modelInst) {
|
|
|
|
callback(err, err ? null : modelInst);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
process.nextTick(callback);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
var originalTrigger = inst.trigger;
|
|
|
|
inst.trigger = function(actionName, work, data, callback) {
|
|
|
|
if (typeof work === 'function') {
|
|
|
|
var originalWork = work;
|
|
|
|
work = function(next) {
|
|
|
|
originalWork.call(this, function(done) {
|
|
|
|
inst.triggerParent(actionName, function(err, inst) {
|
|
|
|
next(done); // TODO [fabien] - error handling?
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
originalTrigger.call(this, actionName, work, data, callback);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsMany.prototype.embeddedList = function(modelInstance) {
|
|
|
|
modelInstance = modelInstance || this.modelInstance;
|
|
|
|
var embeddedList = modelInstance[this.definition.keyFrom] || [];
|
|
|
|
embeddedList.forEach(this.prepareEmbeddedInstance.bind(this));
|
|
|
|
return embeddedList;
|
|
|
|
};
|
|
|
|
|
2014-07-27 14:30:45 +00:00
|
|
|
EmbedsMany.prototype.related = function(receiver, scopeParams, condOrRefresh, cb) {
|
2014-07-29 08:54:28 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var actualCond = {};
|
|
|
|
if (arguments.length === 3) {
|
|
|
|
cb = condOrRefresh;
|
|
|
|
} else if (arguments.length === 4) {
|
2014-08-19 20:10:35 +00:00
|
|
|
if (typeof condOrRefresh === 'object') {
|
2014-07-27 14:30:45 +00:00
|
|
|
actualCond = condOrRefresh;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw new Error('Method can be only called with one or two arguments');
|
|
|
|
}
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
var embeddedList = this.embeddedList(receiver);
|
2014-07-29 08:54:28 +00:00
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
this.definition.applyScope(receiver, actualCond);
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var params = mergeQuery(actualCond, scopeParams);
|
2014-07-29 08:54:28 +00:00
|
|
|
|
2014-08-15 09:28:25 +00:00
|
|
|
if (params.where) { // TODO [fabien] Support order/sorting
|
2014-07-27 14:30:45 +00:00
|
|
|
embeddedList = embeddedList ? embeddedList.filter(applyFilter(params)) : embeddedList;
|
|
|
|
}
|
|
|
|
|
2014-07-29 08:54:28 +00:00
|
|
|
var returnRelated = function(list) {
|
|
|
|
if (params.include) {
|
|
|
|
modelTo.include(list, params.include, cb);
|
|
|
|
} else {
|
|
|
|
process.nextTick(function() { cb(null, list); });
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
returnRelated(embeddedList);
|
2014-07-27 14:30:45 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsMany.prototype.findById = function (fkId, cb) {
|
2014-08-11 13:33:41 +00:00
|
|
|
var pk = this.definition.keyTo;
|
2014-07-27 14:30:45 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
var embeddedList = this.embeddedList();
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var find = function(id) {
|
|
|
|
for (var i = 0; i < embeddedList.length; i++) {
|
|
|
|
var item = embeddedList[i];
|
2014-07-30 11:22:20 +00:00
|
|
|
if (item[pk].toString() === id) return item;
|
2014-07-27 14:30:45 +00:00
|
|
|
}
|
|
|
|
return null;
|
|
|
|
};
|
|
|
|
|
2014-07-30 11:22:20 +00:00
|
|
|
var item = find(fkId.toString()); // in case of explicit id
|
2014-07-27 14:30:45 +00:00
|
|
|
item = (item instanceof modelTo) ? item : null;
|
|
|
|
|
|
|
|
if (typeof cb === 'function') {
|
|
|
|
process.nextTick(function() {
|
|
|
|
cb(null, item);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
return item; // sync
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsMany.prototype.exists = function (fkId, cb) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var inst = this.findById(fkId, function (err, inst) {
|
|
|
|
if (cb) cb(err, inst instanceof modelTo);
|
|
|
|
});
|
|
|
|
return inst instanceof modelTo; // sync
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsMany.prototype.updateById = function (fkId, data, cb) {
|
|
|
|
if (typeof data === 'function') {
|
|
|
|
cb = data;
|
|
|
|
data = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
var modelTo = this.definition.modelTo;
|
2014-08-11 13:33:41 +00:00
|
|
|
var propertyName = this.definition.keyFrom;
|
2014-07-27 14:30:45 +00:00
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
var embeddedList = this.embeddedList();
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var inst = this.findById(fkId);
|
|
|
|
|
|
|
|
if (inst instanceof modelTo) {
|
|
|
|
if (typeof data === 'object') {
|
2014-08-11 11:03:51 +00:00
|
|
|
inst.setAttributes(data);
|
2014-07-27 14:30:45 +00:00
|
|
|
}
|
|
|
|
var err = inst.isValid() ? null : new ValidationError(inst);
|
|
|
|
if (err && typeof cb === 'function') {
|
|
|
|
return process.nextTick(function() {
|
|
|
|
cb(err, inst);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof cb === 'function') {
|
2014-08-11 13:33:41 +00:00
|
|
|
modelInstance.updateAttribute(propertyName,
|
2014-07-27 14:30:45 +00:00
|
|
|
embeddedList, function(err) {
|
|
|
|
cb(err, inst);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} else if (typeof cb === 'function') {
|
|
|
|
process.nextTick(function() {
|
|
|
|
cb(null, null); // not found
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return inst; // sync
|
|
|
|
};
|
|
|
|
|
|
|
|
EmbedsMany.prototype.destroyById = function (fkId, cb) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
2014-08-11 13:33:41 +00:00
|
|
|
var propertyName = this.definition.keyFrom;
|
2014-07-27 14:30:45 +00:00
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
var embeddedList = this.embeddedList();
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-07-29 15:43:30 +00:00
|
|
|
var inst = (fkId instanceof modelTo) ? fkId : this.findById(fkId);
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
if (inst instanceof modelTo) {
|
|
|
|
var index = embeddedList.indexOf(inst);
|
|
|
|
if (index > -1) embeddedList.splice(index, 1);
|
|
|
|
if (typeof cb === 'function') {
|
2014-08-11 13:33:41 +00:00
|
|
|
modelInstance.updateAttribute(propertyName,
|
2014-07-27 14:30:45 +00:00
|
|
|
embeddedList, function(err) {
|
2014-07-30 11:22:20 +00:00
|
|
|
cb(err);
|
2014-08-22 14:02:01 +00:00
|
|
|
modelTo.emit('deleted', inst.id, inst.toJSON());
|
2014-07-27 14:30:45 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
} else if (typeof cb === 'function') {
|
2014-07-30 11:22:20 +00:00
|
|
|
process.nextTick(cb); // not found
|
2014-07-27 14:30:45 +00:00
|
|
|
}
|
|
|
|
return inst; // sync
|
|
|
|
};
|
|
|
|
|
2014-07-29 08:51:33 +00:00
|
|
|
EmbedsMany.prototype.get = EmbedsMany.prototype.findById;
|
|
|
|
EmbedsMany.prototype.set = EmbedsMany.prototype.updateById;
|
2014-07-29 15:43:30 +00:00
|
|
|
EmbedsMany.prototype.unset = EmbedsMany.prototype.destroyById;
|
2014-07-29 08:51:33 +00:00
|
|
|
|
|
|
|
EmbedsMany.prototype.at = function (index, cb) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
var embeddedList = this.embeddedList();
|
2014-07-29 08:51:33 +00:00
|
|
|
|
|
|
|
var item = embeddedList[parseInt(index)];
|
|
|
|
item = (item instanceof modelTo) ? item : null;
|
|
|
|
|
|
|
|
if (typeof cb === 'function') {
|
|
|
|
process.nextTick(function() {
|
|
|
|
cb(null, item);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
return item; // sync
|
|
|
|
};
|
|
|
|
|
2014-07-27 14:30:45 +00:00
|
|
|
EmbedsMany.prototype.create = function (targetModelData, cb) {
|
2014-08-11 13:33:41 +00:00
|
|
|
var pk = this.definition.keyTo;
|
2014-07-27 14:30:45 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
2014-08-11 13:33:41 +00:00
|
|
|
var propertyName = this.definition.keyFrom;
|
2014-07-27 14:30:45 +00:00
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
if (typeof targetModelData === 'function' && !cb) {
|
|
|
|
cb = targetModelData;
|
|
|
|
targetModelData = {};
|
|
|
|
}
|
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
var embeddedList = this.embeddedList();
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-07-27 15:16:25 +00:00
|
|
|
var inst = this.build(targetModelData);
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var err = inst.isValid() ? null : new ValidationError(inst);
|
|
|
|
|
|
|
|
if (err) {
|
2014-07-30 13:01:55 +00:00
|
|
|
return process.nextTick(function() {
|
|
|
|
cb(err);
|
2014-07-27 14:30:45 +00:00
|
|
|
});
|
2014-07-30 11:22:20 +00:00
|
|
|
}
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-08-11 13:33:41 +00:00
|
|
|
modelInstance.updateAttribute(propertyName,
|
2014-07-27 14:30:45 +00:00
|
|
|
embeddedList, function(err, modelInst) {
|
2014-07-30 13:01:55 +00:00
|
|
|
cb(err, err ? null : inst);
|
2014-07-27 14:30:45 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-07-29 15:43:30 +00:00
|
|
|
EmbedsMany.prototype.build = function(targetModelData) {
|
2014-07-27 14:30:45 +00:00
|
|
|
var modelTo = this.definition.modelTo;
|
2014-07-27 15:16:25 +00:00
|
|
|
var modelInstance = this.modelInstance;
|
2014-08-30 09:43:36 +00:00
|
|
|
var forceId = this.definition.options.forceId;
|
|
|
|
var connector = modelTo.dataSource.connector;
|
|
|
|
|
|
|
|
var pk = this.definition.keyTo;
|
|
|
|
var pkProp = modelTo.definition.properties[pk]
|
|
|
|
var pkType = pkProp && pkProp.type;
|
2014-07-27 15:16:25 +00:00
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
var embeddedList = this.embeddedList();
|
2014-07-27 15:16:25 +00:00
|
|
|
|
2014-07-27 14:30:45 +00:00
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
|
2014-08-30 09:43:36 +00:00
|
|
|
var assignId = (forceId || targetModelData[pk] === undefined);
|
|
|
|
|
|
|
|
if (assignId && typeof connector.generateId === 'function') {
|
|
|
|
var id = connector.generateId(modelTo.modelName, targetModelData, pk);
|
|
|
|
targetModelData[pk] = id;
|
|
|
|
} else if (assignId && pkType === Number) {
|
2014-07-27 15:16:25 +00:00
|
|
|
var ids = embeddedList.map(function(m) {
|
|
|
|
return (typeof m[pk] === 'number' ? m[pk] : 0);
|
|
|
|
});
|
2014-07-30 11:22:20 +00:00
|
|
|
if (ids.length > 0) {
|
|
|
|
targetModelData[pk] = Math.max.apply(null, ids) + 1;
|
|
|
|
} else {
|
|
|
|
targetModelData[pk] = 1;
|
|
|
|
}
|
2014-07-27 15:16:25 +00:00
|
|
|
}
|
2014-07-27 14:30:45 +00:00
|
|
|
|
2014-08-19 20:10:35 +00:00
|
|
|
this.definition.applyProperties(modelInstance, targetModelData);
|
2014-07-27 14:30:45 +00:00
|
|
|
|
|
|
|
var inst = new modelTo(targetModelData);
|
|
|
|
|
|
|
|
if (this.definition.options.prepend) {
|
|
|
|
embeddedList.unshift(inst);
|
|
|
|
} else {
|
|
|
|
embeddedList.push(inst);
|
|
|
|
}
|
|
|
|
|
2014-08-15 13:12:02 +00:00
|
|
|
this.prepareEmbeddedInstance(inst);
|
|
|
|
|
2014-07-27 14:30:45 +00:00
|
|
|
return inst;
|
|
|
|
};
|
2014-07-29 13:01:47 +00:00
|
|
|
|
2014-07-29 15:43:30 +00:00
|
|
|
/**
|
|
|
|
* Add the target model instance to the 'embedsMany' relation
|
|
|
|
* @param {Object|ID} acInst The actual instance or id value
|
|
|
|
*/
|
2014-07-29 19:46:12 +00:00
|
|
|
EmbedsMany.prototype.add = function (acInst, data, cb) {
|
|
|
|
if (typeof data === 'function') {
|
|
|
|
cb = data;
|
|
|
|
data = {};
|
|
|
|
}
|
|
|
|
|
2014-07-29 15:43:30 +00:00
|
|
|
var self = this;
|
|
|
|
var definition = this.definition;
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
var options = definition.options;
|
2014-07-29 19:56:59 +00:00
|
|
|
var belongsTo = options.belongsTo && modelTo.relations[options.belongsTo];
|
2014-07-29 15:43:30 +00:00
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
if (!belongsTo) {
|
|
|
|
throw new Error('Invalid reference: ' + options.belongsTo || '(none)');
|
2014-07-29 15:43:30 +00:00
|
|
|
}
|
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
var fk2 = belongsTo.keyTo;
|
|
|
|
var pk2 = belongsTo.modelTo.definition.idName() || 'id';
|
2014-07-29 15:43:30 +00:00
|
|
|
|
|
|
|
var query = {};
|
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst;
|
2014-07-29 15:43:30 +00:00
|
|
|
|
|
|
|
var filter = { where: query };
|
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
belongsTo.applyScope(modelInstance, filter);
|
2014-07-29 15:43:30 +00:00
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
belongsTo.modelTo.findOne(filter, function(err, ref) {
|
|
|
|
if (ref instanceof belongsTo.modelTo) {
|
2014-07-29 19:46:12 +00:00
|
|
|
var inst = self.build(data || {});
|
2014-07-29 19:56:59 +00:00
|
|
|
inst[options.belongsTo](ref);
|
2014-07-29 15:43:30 +00:00
|
|
|
modelInstance.save(function(err) {
|
|
|
|
cb(err, err ? null : inst);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
cb(null, null);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove the target model instance from the 'embedsMany' relation
|
|
|
|
* @param {Object|ID) acInst The actual instance or id value
|
|
|
|
*/
|
|
|
|
EmbedsMany.prototype.remove = function (acInst, cb) {
|
|
|
|
var self = this;
|
|
|
|
var definition = this.definition;
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
var options = definition.options;
|
2014-07-29 19:56:59 +00:00
|
|
|
var belongsTo = options.belongsTo && modelTo.relations[options.belongsTo];
|
2014-07-29 15:43:30 +00:00
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
if (!belongsTo) {
|
|
|
|
throw new Error('Invalid reference: ' + options.belongsTo || '(none)');
|
2014-07-29 15:43:30 +00:00
|
|
|
}
|
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
var fk2 = belongsTo.keyTo;
|
|
|
|
var pk2 = belongsTo.modelTo.definition.idName() || 'id';
|
2014-07-29 15:43:30 +00:00
|
|
|
|
|
|
|
var query = {};
|
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
query[fk2] = (acInst instanceof belongsTo.modelTo) ? acInst[pk2] : acInst;
|
2014-07-29 15:43:30 +00:00
|
|
|
|
|
|
|
var filter = { where: query };
|
|
|
|
|
2014-07-29 19:56:59 +00:00
|
|
|
belongsTo.applyScope(modelInstance, filter);
|
2014-07-29 15:43:30 +00:00
|
|
|
|
2014-08-11 13:33:41 +00:00
|
|
|
modelInstance[definition.name](filter, function(err, items) {
|
2014-07-29 15:43:30 +00:00
|
|
|
if (err) return cb(err);
|
|
|
|
|
|
|
|
items.forEach(function(item) {
|
|
|
|
self.unset(item);
|
|
|
|
});
|
|
|
|
|
|
|
|
modelInstance.save(function(err) {
|
2014-07-30 11:22:20 +00:00
|
|
|
cb(err);
|
2014-07-29 15:43:30 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2014-07-29 13:01:47 +00:00
|
|
|
RelationDefinition.referencesMany = function referencesMany(modelFrom, modelTo, params) {
|
2014-07-29 19:46:12 +00:00
|
|
|
params = params || {};
|
2014-08-09 08:58:03 +00:00
|
|
|
modelTo = lookupModelTo(modelFrom, modelTo, params, true);
|
2014-07-29 19:46:12 +00:00
|
|
|
|
2014-08-09 08:58:03 +00:00
|
|
|
var thisClassName = modelFrom.modelName;
|
2014-07-29 19:46:12 +00:00
|
|
|
var relationName = params.as || i8n.camelize(modelTo.pluralModelName, true);
|
|
|
|
var fk = params.foreignKey || i8n.camelize(modelTo.modelName + '_ids', true);
|
|
|
|
var idName = modelTo.dataSource.idName(modelTo.modelName) || 'id';
|
2014-07-30 05:19:52 +00:00
|
|
|
var idType = modelTo.definition.properties[idName].type;
|
2014-07-29 19:46:12 +00:00
|
|
|
|
|
|
|
var definition = modelFrom.relations[relationName] = new RelationDefinition({
|
|
|
|
name: relationName,
|
|
|
|
type: RelationTypes.referencesMany,
|
|
|
|
modelFrom: modelFrom,
|
|
|
|
keyFrom: fk,
|
|
|
|
keyTo: idName,
|
|
|
|
modelTo: modelTo,
|
|
|
|
multiple: true,
|
|
|
|
properties: params.properties,
|
|
|
|
scope: params.scope,
|
|
|
|
options: params.options
|
|
|
|
});
|
|
|
|
|
|
|
|
modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, {
|
|
|
|
type: [idType], default: function() { return []; }
|
|
|
|
});
|
|
|
|
|
|
|
|
modelFrom.validate(relationName, function(err) {
|
|
|
|
var ids = this[fk] || [];
|
|
|
|
var uniqueIds = ids.filter(function(id, pos) {
|
|
|
|
return ids.indexOf(id) === pos;
|
|
|
|
});
|
|
|
|
if (ids.length !== uniqueIds.length) {
|
2014-08-29 19:30:42 +00:00
|
|
|
var msg = 'contains duplicate `' + modelTo.modelName + '` instance';
|
2014-07-29 19:46:12 +00:00
|
|
|
this.errors.add(relationName, msg, 'uniqueness');
|
|
|
|
err(false);
|
|
|
|
}
|
|
|
|
}, { code: 'uniqueness' })
|
|
|
|
|
|
|
|
var scopeMethods = {
|
|
|
|
findById: scopeMethod(definition, 'findById'),
|
|
|
|
destroy: scopeMethod(definition, 'destroyById'),
|
|
|
|
updateById: scopeMethod(definition, 'updateById'),
|
|
|
|
exists: scopeMethod(definition, 'exists'),
|
|
|
|
add: scopeMethod(definition, 'add'),
|
|
|
|
remove: scopeMethod(definition, 'remove'),
|
|
|
|
at: scopeMethod(definition, 'at')
|
|
|
|
};
|
|
|
|
|
|
|
|
var findByIdFunc = scopeMethods.findById;
|
|
|
|
modelFrom.prototype['__findById__' + relationName] = findByIdFunc;
|
|
|
|
|
|
|
|
var destroyByIdFunc = scopeMethods.destroy;
|
|
|
|
modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc;
|
|
|
|
|
|
|
|
var updateByIdFunc = scopeMethods.updateById;
|
|
|
|
modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc;
|
|
|
|
|
2014-07-30 13:01:55 +00:00
|
|
|
var addFunc = scopeMethods.add;
|
|
|
|
modelFrom.prototype['__link__' + relationName] = addFunc;
|
|
|
|
|
|
|
|
var removeFunc = scopeMethods.remove;
|
|
|
|
modelFrom.prototype['__unlink__' + relationName] = removeFunc;
|
|
|
|
|
2014-07-29 19:46:12 +00:00
|
|
|
scopeMethods.create = scopeMethod(definition, 'create');
|
|
|
|
scopeMethods.build = scopeMethod(definition, 'build');
|
|
|
|
|
2014-07-29 20:59:44 +00:00
|
|
|
scopeMethods.related = scopeMethod(definition, 'related');
|
|
|
|
|
2014-07-30 14:46:05 +00:00
|
|
|
var customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods);
|
|
|
|
|
|
|
|
for (var i = 0; i < customMethods.length; i++) {
|
|
|
|
var methodName = customMethods[i];
|
|
|
|
var method = scopeMethods[methodName];
|
|
|
|
if (typeof method === 'function' && method.shared === true) {
|
|
|
|
modelFrom.prototype['__' + methodName + '__' + relationName] = method;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-07-29 19:46:12 +00:00
|
|
|
// Mix the property and scoped methods into the prototype class
|
|
|
|
var scopeDefinition = defineScope(modelFrom.prototype, modelTo, relationName, function () {
|
|
|
|
return {};
|
2014-08-08 16:25:49 +00:00
|
|
|
}, scopeMethods, definition.options);
|
2014-07-29 19:46:12 +00:00
|
|
|
|
2014-07-29 20:59:44 +00:00
|
|
|
scopeDefinition.related = scopeMethods.related; // bound to definition
|
2014-08-13 09:28:23 +00:00
|
|
|
|
|
|
|
return definition;
|
2014-07-29 19:46:12 +00:00
|
|
|
};
|
2014-07-29 13:01:47 +00:00
|
|
|
|
2014-07-29 19:46:12 +00:00
|
|
|
ReferencesMany.prototype.related = function(receiver, scopeParams, condOrRefresh, cb) {
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var relationName = this.definition.name;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
var self = receiver;
|
|
|
|
|
|
|
|
var actualCond = {};
|
|
|
|
var actualRefresh = false;
|
|
|
|
if (arguments.length === 3) {
|
|
|
|
cb = condOrRefresh;
|
|
|
|
} else if (arguments.length === 4) {
|
|
|
|
if (typeof condOrRefresh === 'boolean') {
|
|
|
|
actualRefresh = condOrRefresh;
|
|
|
|
} else {
|
|
|
|
actualCond = condOrRefresh;
|
|
|
|
actualRefresh = true;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
throw new Error('Method can be only called with one or two arguments');
|
|
|
|
}
|
|
|
|
|
|
|
|
var ids = self[fk] || [];
|
|
|
|
|
|
|
|
this.definition.applyScope(modelInstance, actualCond);
|
|
|
|
|
|
|
|
var params = mergeQuery(actualCond, scopeParams);
|
|
|
|
|
|
|
|
modelTo.findByIds(ids, params, cb);
|
2014-07-29 13:01:47 +00:00
|
|
|
};
|
|
|
|
|
2014-07-29 19:46:12 +00:00
|
|
|
ReferencesMany.prototype.findById = function (fkId, cb) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelFrom = this.definition.modelFrom;
|
|
|
|
var relationName = this.definition.name;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var pk = this.definition.keyTo;
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
|
|
|
|
if (typeof fkId === 'object') {
|
|
|
|
fkId = fkId.toString(); // mongodb
|
|
|
|
}
|
|
|
|
|
|
|
|
var ids = [fkId];
|
|
|
|
|
|
|
|
var filter = {};
|
|
|
|
|
|
|
|
this.definition.applyScope(modelInstance, filter);
|
|
|
|
|
|
|
|
modelTo.findByIds(ids, filter, function (err, instances) {
|
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
var inst = instances[0];
|
|
|
|
if (!inst) {
|
|
|
|
err = new Error('No instance with id ' + fkId + ' found for ' + modelTo.modelName);
|
|
|
|
err.statusCode = 404;
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
var currentIds = ids.map(function(id) { return id.toString(); });
|
|
|
|
var id = (inst[pk] || '').toString(); // mongodb
|
|
|
|
|
|
|
|
// Check if the foreign key is amongst the ids
|
|
|
|
if (currentIds.indexOf(id) > -1) {
|
|
|
|
cb(null, inst);
|
|
|
|
} else {
|
|
|
|
err = new Error('Key mismatch: ' + modelFrom.modelName + '.' + fk
|
|
|
|
+ ': ' + modelInstance[fk]
|
|
|
|
+ ', ' + modelTo.modelName + '.' + pk + ': ' + inst[pk]);
|
|
|
|
err.statusCode = 400;
|
|
|
|
cb(err);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
ReferencesMany.prototype.exists = function (fkId, cb) {
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
var ids = this.modelInstance[fk] || [];
|
|
|
|
var currentIds = ids.map(function(id) { return id.toString(); });
|
|
|
|
var fkId = (fkId || '').toString(); // mongodb
|
|
|
|
process.nextTick(function() { cb(null, currentIds.indexOf(fkId) > -1) });
|
|
|
|
};
|
|
|
|
|
|
|
|
ReferencesMany.prototype.updateById = function (fkId, data, cb) {
|
|
|
|
if (typeof data === 'function') {
|
|
|
|
cb = data;
|
|
|
|
data = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
this.findById(fkId, function(err, inst) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
inst.updateAttributes(data, cb);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
ReferencesMany.prototype.destroyById = function (fkId, cb) {
|
|
|
|
var self = this;
|
|
|
|
this.findById(fkId, function(err, inst) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
self.remove(inst, function(err, ids) {
|
|
|
|
inst.destroy(cb);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
ReferencesMany.prototype.at = function (index, cb) {
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
var ids = this.modelInstance[fk] || [];
|
|
|
|
this.findById(ids[index], cb);
|
|
|
|
};
|
|
|
|
|
|
|
|
ReferencesMany.prototype.create = function (targetModelData, cb) {
|
|
|
|
var definition = this.definition;
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var relationName = this.definition.name;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
var pk = this.definition.keyTo;
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
|
|
|
|
if (typeof targetModelData === 'function' && !cb) {
|
|
|
|
cb = targetModelData;
|
|
|
|
targetModelData = {};
|
|
|
|
}
|
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
|
|
|
|
var ids = modelInstance[fk] || [];
|
|
|
|
|
|
|
|
var inst = this.build(targetModelData);
|
|
|
|
|
|
|
|
inst.save(function(err, inst) {
|
|
|
|
if (err) return cb(err, inst);
|
|
|
|
|
|
|
|
var id = inst[pk];
|
|
|
|
|
|
|
|
if (typeof id === 'object') {
|
|
|
|
id = id.toString(); // mongodb
|
|
|
|
}
|
|
|
|
|
|
|
|
if (definition.options.prepend) {
|
|
|
|
ids.unshift(id);
|
|
|
|
} else {
|
|
|
|
ids.push(id);
|
|
|
|
}
|
|
|
|
|
|
|
|
modelInstance.updateAttribute(fk,
|
|
|
|
ids, function(err, modelInst) {
|
|
|
|
cb(err, inst);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
ReferencesMany.prototype.build = function(targetModelData) {
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
targetModelData = targetModelData || {};
|
|
|
|
|
|
|
|
this.definition.applyProperties(this.modelInstance, targetModelData);
|
|
|
|
|
|
|
|
return new modelTo(targetModelData);
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add the target model instance to the 'embedsMany' relation
|
|
|
|
* @param {Object|ID} acInst The actual instance or id value
|
|
|
|
*/
|
|
|
|
ReferencesMany.prototype.add = function (acInst, cb) {
|
|
|
|
var self = this;
|
|
|
|
var definition = this.definition;
|
|
|
|
var modelTo = this.definition.modelTo;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
var pk = this.definition.keyTo;
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
|
2014-07-30 13:01:55 +00:00
|
|
|
var insert = function(inst, done) {
|
|
|
|
var id = inst[pk];
|
|
|
|
|
2014-07-29 19:46:12 +00:00
|
|
|
if (typeof id === 'object') {
|
|
|
|
id = id.toString(); // mongodb
|
|
|
|
}
|
|
|
|
|
|
|
|
var ids = modelInstance[fk] || [];
|
|
|
|
|
|
|
|
if (definition.options.prepend) {
|
|
|
|
ids.unshift(id);
|
|
|
|
} else {
|
|
|
|
ids.push(id);
|
|
|
|
}
|
|
|
|
|
2014-07-30 13:01:55 +00:00
|
|
|
modelInstance.updateAttribute(fk, ids, function(err) {
|
|
|
|
done(err, err ? null : inst);
|
2014-07-29 19:46:12 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
if (acInst instanceof modelTo) {
|
2014-07-30 13:01:55 +00:00
|
|
|
insert(acInst, cb);
|
2014-07-29 19:46:12 +00:00
|
|
|
} else {
|
|
|
|
var filter = { where: {} };
|
|
|
|
filter.where[pk] = acInst;
|
|
|
|
|
|
|
|
definition.applyScope(modelInstance, filter);
|
|
|
|
|
|
|
|
modelTo.findOne(filter, function (err, inst) {
|
2014-07-30 13:01:55 +00:00
|
|
|
if (err || !inst) return cb(err, null);
|
|
|
|
insert(inst, cb);
|
2014-07-29 19:46:12 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove the target model instance from the 'embedsMany' relation
|
|
|
|
* @param {Object|ID) acInst The actual instance or id value
|
|
|
|
*/
|
|
|
|
ReferencesMany.prototype.remove = function (acInst, cb) {
|
|
|
|
var definition = this.definition;
|
|
|
|
var modelInstance = this.modelInstance;
|
|
|
|
|
|
|
|
var pk = this.definition.keyTo;
|
|
|
|
var fk = this.definition.keyFrom;
|
|
|
|
|
|
|
|
var ids = modelInstance[fk] || [];
|
|
|
|
|
|
|
|
var currentIds = ids.map(function(id) { return id.toString(); });
|
|
|
|
|
|
|
|
var id = (acInst instanceof definition.modelTo) ? acInst[pk] : acInst;
|
|
|
|
id = id.toString();
|
|
|
|
|
|
|
|
var index = currentIds.indexOf(id);
|
|
|
|
if (index > -1) {
|
|
|
|
ids.splice(index, 1);
|
|
|
|
modelInstance.updateAttribute(fk, ids, function(err, inst) {
|
|
|
|
cb(err, inst[fk] || []);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
process.nextTick(function() { cb(null, ids); });
|
|
|
|
}
|
|
|
|
};
|