UNPKG

loopback-datasource-juggler

Version:
1,594 lines (1,418 loc) 110 kB
// Copyright IBM Corp. 2014,2019. All Rights Reserved. // Node module: loopback-datasource-juggler // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT 'use strict'; /*! * Dependencies */ const assert = require('assert'); const util = require('util'); const async = require('async'); const utils = require('./utils'); const i8n = require('inflection'); const defineScope = require('./scope.js').defineScope; const g = require('strong-globalize')(); const mergeQuery = utils.mergeQuery; const idEquals = utils.idEquals; const idsHaveDuplicates = utils.idsHaveDuplicates; const ModelBaseClass = require('./model.js'); const applyFilter = require('./connectors/memory').applyFilter; const ValidationError = require('./validations.js').ValidationError; const deprecated = require('depd')('loopback-datasource-juggler'); const debug = require('debug')('loopback:relations'); const RelationTypes = { belongsTo: 'belongsTo', hasMany: 'hasMany', hasOne: 'hasOne', hasAndBelongsToMany: 'hasAndBelongsToMany', referencesMany: 'referencesMany', embedsOne: 'embedsOne', embedsMany: 'embedsMany', }; const RelationClasses = { belongsTo: BelongsTo, hasMany: HasMany, hasManyThrough: HasManyThrough, hasOne: HasOne, hasAndBelongsToMany: HasAndBelongsToMany, referencesMany: ReferencesMany, embedsOne: EmbedsOne, embedsMany: EmbedsMany, }; exports.Relation = Relation; exports.RelationDefinition = RelationDefinition; exports.RelationTypes = RelationTypes; exports.RelationClasses = RelationClasses; exports.HasMany = HasMany; exports.HasManyThrough = HasManyThrough; exports.HasOne = HasOne; exports.HasAndBelongsToMany = HasAndBelongsToMany; exports.BelongsTo = BelongsTo; exports.ReferencesMany = ReferencesMany; exports.EmbedsOne = EmbedsOne; exports.EmbedsMany = EmbedsMany; function normalizeType(type) { if (!type) { return type; } const t1 = type.toLowerCase(); for (const t2 in RelationTypes) { if (t2.toLowerCase() === t1) { return t2; } } return null; } function extendScopeMethods(definition, scopeMethods, ext) { let customMethods = []; let relationClass = RelationClasses[definition.type]; if (definition.type === RelationTypes.hasMany && definition.modelThrough) { relationClass = RelationClasses.hasManyThrough; } if (typeof ext === 'function') { customMethods = ext.call(definition, scopeMethods, relationClass); } else if (typeof ext === 'object') { function createFunc(definition, relationMethod) { return function() { const relation = new relationClass(definition, this); return relationMethod.apply(relation, arguments); }; } for (const key in ext) { const relationMethod = ext[key]; const method = scopeMethods[key] = createFunc(definition, relationMethod); if (relationMethod.shared) { sharedMethod(definition, key, method, relationMethod); } customMethods.push(key); } } return [].concat(customMethods || []); } function bindRelationMethods(relation, relationMethod, definition) { const methods = definition.methods || {}; Object.keys(methods).forEach(function(m) { if (typeof methods[m] !== 'function') return; relationMethod[m] = methods[m].bind(relation); }); } function preventFkOverride(inst, data, fkProp) { if (!fkProp) return undefined; if (data[fkProp] !== undefined && !idEquals(data[fkProp], inst[fkProp])) { return new Error(g.f( 'Cannot override foreign key %s from %s to %s', fkProp, inst[fkProp], data[fkProp], )); } } /** * 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; assert(this.modelFrom, 'Source model is required'); this.keyFrom = definition.keyFrom; this.modelTo = definition.modelTo; this.keyTo = definition.keyTo; this.polymorphic = definition.polymorphic; if (typeof this.polymorphic !== 'object') { assert(this.modelTo, 'Target model is required'); } this.modelThrough = definition.modelThrough; this.keyThrough = definition.keyThrough; this.multiple = definition.multiple; this.properties = definition.properties || {}; this.options = definition.options || {}; this.scope = definition.scope; this.embed = definition.embed === true; this.methods = definition.methods || {}; } RelationDefinition.prototype.toJSON = function() { const polymorphic = typeof this.polymorphic === 'object'; let modelToName = this.modelTo && this.modelTo.modelName; if (!modelToName && polymorphic && this.type === 'belongsTo') { modelToName = '<polymorphic>'; } const json = { name: this.name, type: this.type, modelFrom: this.modelFrom.modelName, keyFrom: this.keyFrom, modelTo: modelToName, keyTo: this.keyTo, multiple: this.multiple, }; if (this.modelThrough) { json.modelThrough = this.modelThrough.modelName; json.keyThrough = this.keyThrough; } if (polymorphic) { json.polymorphic = this.polymorphic; } return json; }; /** * Define a relation scope method * @param {String} name of the method * @param {Function} function to define */ RelationDefinition.prototype.defineMethod = function(name, fn) { const relationClass = RelationClasses[this.type]; const relationName = this.name; const modelFrom = this.modelFrom; const definition = this; let method; if (definition.multiple) { const scope = this.modelFrom.scopes[this.name]; if (!scope) throw new Error(g.f('Unknown relation {{scope}}: %s', this.name)); method = scope.defineMethod(name, function() { const relation = new relationClass(definition, this); return fn.apply(relation, arguments); }); } else { definition.methods[name] = fn; method = function() { const rel = this[relationName]; return rel[name].apply(rel, arguments); }; } if (method && fn.shared) { sharedMethod(definition, name, method, fn); modelFrom.prototype['__' + name + '__' + relationName] = method; } return method; }; /** * 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) { filter = filter || {}; filter.where = filter.where || {}; if ((this.type !== 'belongsTo' || this.type === 'hasOne') && typeof this.polymorphic === 'object') { // polymorphic const discriminator = this.polymorphic.discriminator; if (this.polymorphic.invert) { filter.where[discriminator] = this.modelTo.modelName; } else { filter.where[discriminator] = this.modelFrom.modelName; } } let scope; if (typeof this.scope === 'function') { scope = this.scope.call(this, modelInstance, filter); } else { scope = this.scope; } if (typeof scope === 'object') { mergeQuery(filter, scope); } }; /** * Apply the configured properties to the target object. * @param {Object} modelInstance * @param {Object} target */ RelationDefinition.prototype.applyProperties = function(modelInstance, obj) { let source = modelInstance, target = obj; if (this.options.invertProperties) { source = obj; target = modelInstance; } if (this.options.embedsProperties) { target = target.__data[this.name] = {}; target[this.keyTo] = source[this.keyTo]; } let k, key; if (typeof this.properties === 'function') { const data = this.properties.call(this, source, target); for (k in data) { target[k] = data[k]; } } else if (Array.isArray(this.properties)) { for (k = 0; k < this.properties.length; k++) { key = this.properties[k]; target[key] = source[key]; } } else if (typeof this.properties === 'object') { for (k in this.properties) { key = this.properties[k]; target[key] = source[k]; } } if ((this.type !== 'belongsTo' || this.type === 'hasOne') && typeof this.polymorphic === 'object') { // polymorphic const discriminator = this.polymorphic.discriminator; if (this.polymorphic.invert) { target[discriminator] = this.modelTo.modelName; } else { target[discriminator] = this.modelFrom.modelName; } } }; /** * 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; } 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]; }; Relation.prototype.callScopeMethod = function(methodName) { const args = Array.prototype.slice.call(arguments, 1); const modelInstance = this.modelInstance; const rel = modelInstance[this.definition.name]; if (rel && typeof rel[methodName] === 'function') { return rel[methodName].apply(rel, args); } else { throw new Error(g.f('Unknown scope method: %s', methodName)); } }; /** * Fetch the related model(s) - this is a helper method to unify access. * @param (Boolean|Object} condOrRefresh refresh or conditions object * @param {Object} [options] Options * @param {Function} cb callback */ Relation.prototype.fetch = function(condOrRefresh, options, cb) { this.modelInstance[this.definition.name].apply(this.modelInstance, arguments); }; /** * 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); HasMany.prototype.removeFromCache = function(id) { const cache = this.modelInstance.__cachedRelations[this.definition.name]; const idName = this.definition.modelTo.definition.idName(); if (Array.isArray(cache)) { for (let i = 0, n = cache.length; i < n; i++) { if (idEquals(cache[i][idName], id)) { return cache.splice(i, 1); } } } return null; }; HasMany.prototype.addToCache = function(inst) { if (!inst) { return; } let cache = this.modelInstance.__cachedRelations[this.definition.name]; if (cache === undefined) { cache = this.modelInstance.__cachedRelations[this.definition.name] = []; } const idName = this.definition.modelTo.definition.idName(); if (Array.isArray(cache)) { for (let i = 0, n = cache.length; i < n; i++) { if (idEquals(cache[i][idName], inst[idName])) { cache[i] = inst; return; } } cache.push(inst); } }; /** * 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); /** * EmbedsOne subclass * @param {RelationDefinition|Object} definition * @param {Object} modelInstance * @returns {EmbedsOne} * @constructor * @class EmbedsOne */ function EmbedsOne(definition, modelInstance) { if (!(this instanceof EmbedsOne)) { return new EmbedsOne(definition, modelInstance); } assert(definition.type === RelationTypes.embedsOne); Relation.apply(this, arguments); } util.inherits(EmbedsOne, Relation); /** * 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); /** * ReferencesMany subclass * @param {RelationDefinition|Object} definition * @param {Object} modelInstance * @returns {ReferencesMany} * @constructor * @class ReferencesMany */ function ReferencesMany(definition, modelInstance) { if (!(this instanceof ReferencesMany)) { return new ReferencesMany(definition, modelInstance); } assert(definition.type === RelationTypes.referencesMany); Relation.apply(this, arguments); } util.inherits(ReferencesMany, Relation); /*! * Find the relation by foreign key * @param {*} foreignKey The foreign key * @returns {Array} The array of matching relation objects */ function findBelongsTo(modelFrom, modelTo, keyTo) { return Object.keys(modelFrom.relations) .map(function(k) { return modelFrom.relations[k]; }) .filter(function(rel) { return (rel.type === RelationTypes.belongsTo && rel.modelTo === modelTo && (keyTo === undefined || rel.keyTo === keyTo)); }) .map(function(rel) { return rel.keyFrom; }); } /*! * 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]; } const lookupClassName = modelName.toLowerCase(); for (const name in models) { if (name.toLowerCase() === lookupClassName) { return models[name]; } } } /* * @param {Object} modelFrom Instance of the 'from' model * @param {Object|String} modelToRef Reference to Model object to which you are * creating the relation: model instance, model name, or name of relation to model. * @param {Object} params The relation params * @param {Boolean} singularize Whether the modelToRef should be singularized when * looking-up modelTo * @return {Object} modelTo Instance of the 'to' model */ function lookupModelTo(modelFrom, modelToRef, params, singularize) { let modelTo; if (typeof modelToRef !== 'string') { // modelToRef might already be an instance of model modelTo = modelToRef; } else { // lookup modelTo based on relation params and modelToRef let modelToName; modelTo = params.model || modelToRef; // modelToRef might be modelTo name if (typeof modelTo === 'string') { // lookup modelTo by name modelToName = modelTo; modelToName = (singularize ? i8n.singularize(modelToName) : modelToName).toLowerCase(); modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName); } if (!modelTo) { // lookup by modelTo name was not successful. Now looking-up by relationTo name const relationToName = params.as || modelToRef; // modelToRef might be relationTo name modelToName = (singularize ? i8n.singularize(relationToName) : relationToName).toLowerCase(); modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName); } } if (typeof modelTo !== 'function') { throw new Error(g.f('Could not find relation %s for model %s', params.as, modelFrom.modelName)); } return modelTo; } /* * Normalize relation's parameter `as` * @param {Object} params The relation params * @param {String} relationName The relation name * @returns {Object} The normalized parameters * NOTE: normalizeRelationAs() mutates the params object */ function normalizeRelationAs(params, relationName) { if (typeof relationName === 'string') { params.as = params.as || relationName; } return params; } /* * Normalize relation's polymorphic parameters * @param {Object|String|Boolean} polymorphic Param `polymorphic` of the relation. * @param {String} relationName The name of the relation we are currently setting up. * @returns {Object} The normalized parameters */ function normalizePolymorphic(polymorphic, relationName) { assert(polymorphic, 'polymorphic param can\'t be false, null or undefined'); assert(!Array.isArray(polymorphic, 'unexpected type for polymorphic param: \'Array\'')); let selector; if (typeof polymorphic === 'string') { // relation type is different from belongsTo (hasMany, hasManyThrough, hasAndBelongsToMany, ...) // polymorphic is the name of the matching belongsTo relation from modelTo to modelFrom selector = polymorphic; } if (polymorphic === true) { // relation type is belongsTo: the relation name is used as the polymorphic selector selector = relationName; } // NOTE: use of `polymorphic.as` keyword will be deprecated in LoopBack.next // to avoid confusion with keyword `as` used at the root of the relation definition object // It is replaced with the `polymorphic.selector` keyword if (typeof polymorphic == 'object') { selector = polymorphic.selector || polymorphic.as; } // relationName is eventually used as selector if provided and selector not already defined // it ultimately defaults to 'reference' selector = selector || relationName || 'reference'; // make sure polymorphic is an object if (typeof polymorphic !== 'object') { polymorphic = {}; } polymorphic.selector = selector; polymorphic.foreignKey = polymorphic.foreignKey || i8n.camelize(selector + '_id', true); // defaults to {{selector}}Id polymorphic.discriminator = polymorphic.discriminator || i8n.camelize(selector + '_type', true); // defaults to {{selectorName}}Type return polymorphic; } /** * 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} modelToRef Reference to Model object to which you are * creating the relation: model instance, model name, or name of relation to model. * @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, modelToRef, params) { const thisClassName = modelFrom.modelName; params = params || {}; normalizeRelationAs(params, modelToRef); const modelTo = lookupModelTo(modelFrom, modelToRef, params, true); const relationName = params.as || i8n.camelize(modelTo.pluralModelName, true); let fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true); let keyThrough = params.keyThrough || i8n.camelize(modelTo.modelName + '_id', true); const pkName = params.primaryKey || modelFrom.dataSource.idName(modelFrom.modelName) || 'id'; let discriminator, polymorphic; if (params.polymorphic) { polymorphic = normalizePolymorphic(params.polymorphic, relationName); if (params.invert) { polymorphic.invert = true; keyThrough = polymorphic.foreignKey; } discriminator = polymorphic.discriminator; if (!params.invert) { fk = polymorphic.foreignKey; } if (!params.through) { modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, {type: 'string', index: true}); } } const definition = new RelationDefinition({ name: relationName, type: RelationTypes.hasMany, modelFrom: modelFrom, keyFrom: pkName, keyTo: fk, modelTo: modelTo, multiple: true, properties: params.properties, scope: params.scope, options: params.options, keyThrough: keyThrough, polymorphic: polymorphic, }); definition.modelThrough = params.through; modelFrom.relations[relationName] = definition; if (!params.through) { // obviously, modelTo should have attribute called `fk` // for polymorphic relations, it is assumed to share the same fk type for all // polymorphic models modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName, pkName); } const scopeMethods = { findById: scopeMethod(definition, 'findById'), destroy: scopeMethod(definition, 'destroyById'), updateById: scopeMethod(definition, 'updateById'), exists: scopeMethod(definition, 'exists'), }; const findByIdFunc = scopeMethods.findById; modelFrom.prototype['__findById__' + relationName] = findByIdFunc; const destroyByIdFunc = scopeMethods.destroy; modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc; const updateByIdFunc = scopeMethods.updateById; modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc; const existsByIdFunc = scopeMethods.exists; modelFrom.prototype['__exists__' + relationName] = existsByIdFunc; if (definition.modelThrough) { scopeMethods.create = scopeMethod(definition, 'create'); scopeMethods.add = scopeMethod(definition, 'add'); scopeMethods.remove = scopeMethod(definition, 'remove'); const addFunc = scopeMethods.add; modelFrom.prototype['__link__' + relationName] = addFunc; const removeFunc = scopeMethods.remove; modelFrom.prototype['__unlink__' + relationName] = removeFunc; } else { scopeMethods.create = scopeMethod(definition, 'create'); scopeMethods.build = scopeMethod(definition, 'build'); } const customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods); for (let i = 0; i < customMethods.length; i++) { const methodName = customMethods[i]; const method = scopeMethods[methodName]; if (typeof method === 'function' && method.shared === true) { modelFrom.prototype['__' + methodName + '__' + relationName] = method; } } // Mix the property and scoped methods into the prototype class defineScope(modelFrom.prototype, params.through || modelTo, relationName, function() { const filter = {}; filter.where = {}; filter.where[fk] = this[pkName]; definition.applyScope(this, filter); if (definition.modelThrough) { let throughRelationName; // find corresponding belongsTo relations from through model as collect for (const r in definition.modelThrough.relations) { const relation = definition.modelThrough.relations[r]; // should be a belongsTo and match modelTo and keyThrough // if relation is polymorphic then check keyThrough only if (relation.type === RelationTypes.belongsTo && (relation.polymorphic && !relation.modelTo || relation.modelTo === definition.modelTo) && (relation.keyFrom === definition.keyThrough) ) { throughRelationName = relation.name; break; } } if (definition.polymorphic && definition.polymorphic.invert) { filter.collect = definition.polymorphic.selector; filter.include = filter.collect; } else { filter.collect = throughRelationName || i8n.camelize(modelTo.modelName, true); filter.include = filter.collect; } } return filter; }, scopeMethods, definition.options); return definition; }; function scopeMethod(definition, methodName) { let relationClass = RelationClasses[definition.type]; if (definition.type === RelationTypes.hasMany && definition.modelThrough) { relationClass = RelationClasses.hasManyThrough; } const method = function() { const relation = new relationClass(definition, this); return relation[methodName].apply(relation, arguments); }; const relationMethod = relationClass.prototype[methodName]; if (relationMethod.shared) { sharedMethod(definition, methodName, method, relationMethod); } return method; } 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; } /** * Find a related item by foreign key * @param {*} fkId The foreign key * @param {Object} [options] Options * @param {Function} cb The callback function */ HasMany.prototype.findById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const modelTo = this.definition.modelTo; const modelFrom = this.definition.modelFrom; const fk = this.definition.keyTo; const pk = this.definition.keyFrom; const modelInstance = this.modelInstance; const idName = this.definition.modelTo.definition.idName(); const filter = {}; filter.where = {}; filter.where[idName] = fkId; filter.where[fk] = modelInstance[pk]; cb = cb || utils.createPromiseCallback(); if (filter.where[fk] === undefined) { // Foreign key is undefined process.nextTick(cb); return cb.promise; } this.definition.applyScope(modelInstance, filter); modelTo.findOne(filter, options, function(err, inst) { if (err) { return cb(err); } if (!inst) { err = new Error(g.f('No instance with {{id}} %s found for %s', fkId, modelTo.modelName)); err.statusCode = 404; return cb(err); } // Check if the foreign key matches the primary key if (inst[fk] != null && idEquals(inst[fk], modelInstance[pk])) { cb(null, inst); } else { err = new Error(g.f('Key mismatch: %s.%s: %s, %s.%s: %s', modelFrom.modelName, pk, modelInstance[pk], modelTo.modelName, fk, inst[fk])); err.statusCode = 400; cb(err); } }); return cb.promise; }; /** * Find a related item by foreign key * @param {*} fkId The foreign key * @param {Object} [options] Options * @param {Function} cb The callback function */ HasMany.prototype.exists = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const fk = this.definition.keyTo; const pk = this.definition.keyFrom; const modelInstance = this.modelInstance; cb = cb || utils.createPromiseCallback(); this.findById(fkId, function(err, inst) { if (err) { return cb(err); } if (!inst) { return cb(null, false); } // Check if the foreign key matches the primary key if (inst[fk] && inst[fk].toString() === modelInstance[pk].toString()) { cb(null, true); } else { cb(null, false); } }); return cb.promise; }; /** * Update a related item by foreign key * @param {*} fkId The foreign key * @param {Object} Changes to the data * @param {Object} [options] Options * @param {Function} cb The callback function */ HasMany.prototype.updateById = function(fkId, data, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } cb = cb || utils.createPromiseCallback(); const fk = this.definition.keyTo; this.findById(fkId, options, function(err, inst) { if (err) { return cb && cb(err); } // Ensure Foreign Key cannot be changed! const fkErr = preventFkOverride(inst, data, fk); if (fkErr) return cb(fkErr); inst.updateAttributes(data, options, cb); }); return cb.promise; }; /** * Delete a related item by foreign key * @param {*} fkId The foreign key * @param {Object} [options] Options * @param {Function} cb The callback function */ HasMany.prototype.destroyById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } cb = cb || utils.createPromiseCallback(); const self = this; this.findById(fkId, options, function(err, inst) { if (err) { return cb(err); } self.removeFromCache(fkId); inst.destroy(options, cb); }); return cb.promise; }; const throughKeys = function(definition) { const modelThrough = definition.modelThrough; const pk2 = definition.modelTo.definition.idName(); let fk1, fk2; if (typeof definition.polymorphic === 'object') { // polymorphic fk1 = definition.keyTo; if (definition.polymorphic.invert) { fk2 = definition.polymorphic.foreignKey; } else { fk2 = definition.keyThrough; } } else if (definition.modelFrom === definition.modelTo) { return findBelongsTo(modelThrough, definition.modelTo, pk2). sort(function(fk1, fk2) { // Fix for bug - https://github.com/strongloop/loopback-datasource-juggler/issues/571 // Make sure that first key is mapped to modelFrom // & second key to modelTo. Order matters return (definition.keyTo === fk1) ? -1 : 1; }); } else { fk1 = findBelongsTo(modelThrough, definition.modelFrom, definition.keyFrom)[0]; fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2)[0]; } return [fk1, fk2]; }; /** * Find a related item by foreign key * @param {*} fkId The foreign key value * @param {Object} [options] Options * @param {Function} cb The callback function */ HasManyThrough.prototype.findById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const self = this; const modelTo = this.definition.modelTo; const pk = this.definition.keyFrom; const modelInstance = this.modelInstance; const modelThrough = this.definition.modelThrough; cb = cb || utils.createPromiseCallback(); self.exists(fkId, options, function(err, exists) { if (err || !exists) { if (!err) { err = new Error(g.f('No relation found in %s' + ' for (%s.%s,%s.%s)', modelThrough.modelName, self.definition.modelFrom.modelName, modelInstance[pk], modelTo.modelName, fkId)); err.statusCode = 404; } return cb(err); } modelTo.findById(fkId, options, function(err, inst) { if (err) { return cb(err); } if (!inst) { err = new Error(g.f('No instance with id %s found for %s', fkId, modelTo.modelName)); err.statusCode = 404; return cb(err); } cb(err, inst); }); }); return cb.promise; }; /** * Delete a related item by foreign key * @param {*} fkId The foreign key * @param {Object} [options] Options * @param {Function} cb The callback function */ HasManyThrough.prototype.destroyById = function(fkId, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const self = this; const modelTo = this.definition.modelTo; const pk = this.definition.keyFrom; const modelInstance = this.modelInstance; const modelThrough = this.definition.modelThrough; cb = cb || utils.createPromiseCallback(); self.exists(fkId, options, function(err, exists) { if (err || !exists) { if (!err) { err = new Error(g.f('No record found in %s for (%s.%s ,%s.%s)', modelThrough.modelName, self.definition.modelFrom.modelName, modelInstance[pk], modelTo.modelName, fkId)); err.statusCode = 404; } return cb(err); } self.remove(fkId, options, function(err) { if (err) { return cb(err); } modelTo.deleteById(fkId, options, cb); }); }); return cb.promise; }; // 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, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const self = this; const definition = this.definition; const modelTo = definition.modelTo; const modelThrough = definition.modelThrough; if (typeof data === 'function' && !cb) { cb = data; data = {}; } cb = cb || utils.createPromiseCallback(); const modelInstance = this.modelInstance; // First create the target model modelTo.create(data, options, function(err, to) { if (err) { return cb(err, to); } // The primary key for the target model const pk2 = definition.modelTo.definition.idName(); const keys = throughKeys(definition); const fk1 = keys[0]; const fk2 = keys[1]; function createRelation(to, next) { const d = {}, q = {}, filter = {where: q}; d[fk1] = q[fk1] = modelInstance[definition.keyFrom]; d[fk2] = q[fk2] = to[pk2]; definition.applyProperties(modelInstance, d); definition.applyScope(modelInstance, filter); // Then create the through model modelThrough.findOrCreate(filter, d, options, function(e, through) { if (e) { // Undo creation of the target model to.destroy(options, function() { next(e); }); } else { self.addToCache(to); next(err, to); } }); } // process array or single item if (!Array.isArray(to)) createRelation(to, cb); else async.map(to, createRelation, cb); }); return cb.promise; }; /** * Add the target model instance to the 'hasMany' relation * @param {Object|ID} acInst The actual instance or id value * @param {Object} [data] Optional data object for the through model to be created * @param {Object} [options] Options * @param {Function} [cb] Callback function */ HasManyThrough.prototype.add = function(acInst, data, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const self = this; const definition = this.definition; const modelThrough = definition.modelThrough; const pk1 = definition.keyFrom; if (typeof data === 'function') { cb = data; data = {}; } const query = {}; data = data || {}; cb = cb || utils.createPromiseCallback(); // The primary key for the target model const pk2 = definition.modelTo.definition.idName(); const keys = throughKeys(definition); const fk1 = keys[0]; const fk2 = keys[1]; query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; const filter = {where: query}; definition.applyScope(this.modelInstance, filter); data[fk1] = this.modelInstance[pk1]; data[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; definition.applyProperties(this.modelInstance, data); // Create an instance of the through model modelThrough.findOrCreate(filter, data, options, function(err, ac) { if (!err) { if (acInst instanceof definition.modelTo) { self.addToCache(acInst); } } cb(err, ac); }); return cb.promise; }; /** * 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, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const definition = this.definition; const modelThrough = definition.modelThrough; const pk1 = definition.keyFrom; const query = {}; // The primary key for the target model const pk2 = definition.modelTo.definition.idName(); const keys = throughKeys(definition); const fk1 = keys[0]; const fk2 = keys[1]; query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; const filter = {where: query}; definition.applyScope(this.modelInstance, filter); cb = cb || utils.createPromiseCallback(); modelThrough.count(filter.where, options, function(err, ac) { cb(err, ac > 0); }); return cb.promise; }; /** * Remove the target model instance from the 'hasMany' relation * @param {Object|ID) acInst The actual instance or id value */ HasManyThrough.prototype.remove = function(acInst, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const self = this; const definition = this.definition; const modelThrough = definition.modelThrough; const pk1 = definition.keyFrom; const query = {}; // The primary key for the target model const pk2 = definition.modelTo.definition.idName(); const keys = throughKeys(definition); const fk1 = keys[0]; const fk2 = keys[1]; query[fk1] = this.modelInstance[pk1]; query[fk2] = (acInst instanceof definition.modelTo) ? acInst[pk2] : acInst; const filter = {where: query}; definition.applyScope(this.modelInstance, filter); cb = cb || utils.createPromiseCallback(); modelThrough.deleteAll(filter.where, options, function(err) { if (!err) { self.removeFromCache(query[fk2]); } cb(err); }); return cb.promise; }; /** * 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 {Object|String} modelToRef Reference to Model object to which you are * creating the relation: model instance, model name, or name of relation to model. * @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, modelToRef, params) { let modelTo, discriminator, polymorphic; params = params || {}; let pkName, relationName, fk; if (params.polymorphic) { relationName = params.as || (typeof modelToRef === 'string' ? modelToRef : null); polymorphic = normalizePolymorphic(params.polymorphic, relationName); modelTo = null; // will be looked-up dynamically pkName = params.primaryKey || params.idName || 'id'; fk = polymorphic.foreignKey; discriminator = polymorphic.discriminator; if (polymorphic.idType) { // explicit key type modelFrom.dataSource.defineProperty(modelFrom.modelName, fk, {type: polymorphic.idType, index: true}); } else { // try to use the same foreign key type as modelFrom modelFrom.dataSource.defineForeignKey(modelFrom.modelName, fk, modelFrom.modelName, pkName); } modelFrom.dataSource.defineProperty(modelFrom.modelName, discriminator, {type: 'string', index: true}); } else { // relation is not polymorphic normalizeRelationAs(params, modelToRef); modelTo = lookupModelTo(modelFrom, modelToRef, params); pkName = params.primaryKey || modelTo.dataSource.idName(modelTo.modelName) || 'id'; relationName = params.as || i8n.camelize(modelTo.modelName, true); fk = params.foreignKey || relationName + 'Id'; modelFrom.dataSource.defineForeignKey(modelFrom.modelName, fk, modelTo.modelName, pkName); } const definition = modelFrom.relations[relationName] = new RelationDefinition({ name: relationName, type: RelationTypes.belongsTo, modelFrom: modelFrom, keyFrom: fk, keyTo: pkName, modelTo: modelTo, multiple: false, properties: params.properties, scope: params.scope, options: params.options, polymorphic: polymorphic, methods: params.methods, }); // 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() { const relation = new BelongsTo(definition, this); const relationMethod = relation.related.bind(relation); relationMethod.get = relation.get.bind(relation); relationMethod.getAsync = function() { deprecated(g.f('BelongsTo method "getAsync()" is deprecated, use "get()" instead.')); return this.get.apply(this, arguments); }; 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); relationMethod._targetClass = definition.modelTo.modelName; } bindRelationMethods(relation, relationMethod, definition); return relationMethod; }, }); // FIXME: [rfeng] Wrap the property into a function for remoting // so that it can be accessed as /api/<model>/<id>/<belongsToRelationName> // For example, /api/orders/1/customer const fn = function() { const f = this[relationName]; f.apply(this, arguments); }; modelFrom.prototype['__get__' + relationName] = fn; return definition; }; BelongsTo.prototype.create = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const self = this; const modelTo = this.definition.modelTo; const fk = this.definition.keyFrom; const pk = this.definition.keyTo; const modelInstance = this.modelInstance; if (typeof targetModelData === 'function' && !cb) { cb = targetModelData; targetModelData = {}; } cb = cb || utils.createPromiseCallback(); this.definition.applyProperties(modelInstance, targetModelData || {}); modelTo.create(targetModelData, options, function(err, targetModel) { if (!err) { modelInstance[fk] = targetModel[pk]; if (modelInstance.isNewRecord()) { self.resetCache(targetModel); cb && cb(err, targetModel); } else { modelInstance.save(options, function(err, inst) { if (cb && err) return cb && cb(err); self.resetCache(targetModel); cb && cb(err, targetModel); }); } } else { cb && cb(err); } }); return cb.promise; }; BelongsTo.prototype.build = function(targetModelData) { const modelTo = this.definition.modelTo; this.definition.applyProperties(this.modelInstance, targetModelData || {}); return new modelTo(targetModelData); }; BelongsTo.prototype.update = function(targetModelData, options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } cb = cb || utils.createPromiseCallback(); const definition = this.definition; const fk = definition.keyTo; this.fetch(options, function(err, inst) { if (inst instanceof ModelBaseClass) { // Ensures Foreign Key cannot be changed! const fkErr = preventFkOverride(inst, targetModelData, fk); if (fkErr) return cb(fkErr); inst.updateAttributes(targetModelData, options, cb); } else { cb(new Error(g.f('{{BelongsTo}} relation %s is empty', definition.name))); } }); return cb.promise; }; BelongsTo.prototype.destroy = function(options, cb) { if (typeof options === 'function' && cb === undefined) { cb = options; options = {}; } const definition = this.definition; const modelInstance = this.modelInstance; const fk = definition.keyFrom; cb = cb || utils.createPromiseCallback(); this.fetch(options, function(err, targetModel) { if (targetModel instanceof ModelBaseClass) { modelInstance[fk] = null; modelInstance.save(options, function(err, targetModel) { if (cb && err) return cb && cb(err); cb && cb(err, targetModel); }); } else { cb(new Error(g.f('{{BelongsTo}} relation %s is empty', definition.name))); } }); return cb.promise; }; /** * Define the method for the belongsTo relation itself * It will support one of the following styles: * - order.customer(refresh, options, 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(condOrRefresh, options, cb) { const self = this; const modelFrom = this.definition.modelFrom; let modelTo = this.definition.modelTo; const pk = this.definition.keyTo; const fk = this.definition.keyFrom; const modelInstance = this.modelInstance; let discriminator; let scopeQuery = null; let newValue; if ((condOrRefresh instanceof ModelBaseClass) && options === undefined && cb === undefined) { // order.customer(customer) newValue = condOrRefresh; condOrRefresh = false; } else if (typeof condOrRefresh === 'function' && options === undefined && cb === undefined) { // order.customer(cb) cb = condOrRefresh; condOrRefresh = false; } else if (typeof options === 'function' && cb === undefined) { // order.customer(condOrRefresh, cb) cb = options; options = {}; } if (!newValue) { scopeQuery = condOrRefresh; } if (typeof this.definition.polymorphic === 'object') { discriminator = this.definition.polymorphic.discriminator; } let cachedValue; if (!condOrRefresh) { cachedValue = self.getCache(); } if (newValue) { // acts as setter modelInstance[fk] = newValue[pk]; if (discriminator) { modelInstance[discriminator] = newValue.constructor.modelName; } this.definition.applyProperties(modelInstance, newValue); self.resetCache(newValue); } else if (typeof cb === 'function') { // acts as async getter if (discriminator) { let modelToName = modelInstance[discriminator]; if (typeof modelToName !== 'string') { throw new Error(g.f('{{Polymorphic}} model not found: `%s` not set', discriminator)); } modelToName = modelToName.toLowerCase(); modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName); if (!modelTo) { throw new Error(g.f('{{Polymorphic}} model not found: `%s`', modelToName)); } } if (cachedValue === undefined || !(cachedValue instanceof ModelBaseClass)) { const query = {where: {}}; query.where[pk] = modelInstance[fk]; if (query.where[pk] === undefined || query.where[pk] === null) { // Foreign key is undefined return process.nextTick(cb); } this.definition.applyScope(modelInstance, query); if (scopeQuery) mergeQuery(query, scopeQuery); if (Array.isArray(query.fields) && query.fields.indexOf(pk) === -1) { query.fields.push(pk); // always include the pk } modelTo.findOne(query, options, function(err, inst) { if (err) { return cb(err); } if (!inst) { return cb(null, null); } // Check if the foreign key matches the primary key if (inst[pk] != null && modelInstance[fk] != null && inst[pk].toString() === modelInstance[fk].toString()) { self.resetCache(inst); cb(null, inst); } else { err = new Error(g.f('Key mismatch: %s.%s: %s, %s.%s: %s', self.definition.modelFrom.modelName, fk, modelInstance[fk], modelTo.modelName, pk, inst[pk])); err.statusCode = 400; cb(err); } }); return modelInstance[fk]; } else { cb(null, cachedValue);