847 lines
32 KiB
JavaScript
Raw Normal View History

2016-03-18 11:12:50 +01:00
'use strict';
/**
* Module dependencies
*/
// Core
const path = require('path');
2016-03-18 11:12:50 +01:00
// Public node modules.
const _ = require('lodash');
const bookshelf = require('bookshelf');
const pluralize = require('pluralize');
// Local helpers.
const utils = require('./utils/');
// Strapi helpers for models.
const utilsModels = require('strapi-utils').models;
2016-03-18 11:12:50 +01:00
2017-02-15 14:43:09 +01:00
const PIVOT_PREFIX = '_pivot_';
const GLOBALS = {};
2017-02-15 14:43:09 +01:00
2016-03-18 11:12:50 +01:00
/**
* Bookshelf hook
*/
module.exports = function(strapi) {
2016-03-18 11:12:50 +01:00
const hook = {
/**
* Default options
*/
defaults: {
defaultConnection: 'default',
host: 'localhost'
2016-03-18 11:12:50 +01:00
},
/**
* Initialize the hook
*/
initialize: cb => {
const connections = _.pickBy(strapi.config.connections, { connector: 'strapi-bookshelf' });
2017-07-24 19:58:03 +02:00
_.forEach(connections, (connection, connectionName) => {
2017-07-24 19:58:03 +02:00
// Apply defaults
2017-07-26 18:53:48 +02:00
_.defaults(connection.settings, strapi.config.hook.settings.bookshelf);
2017-07-24 19:58:03 +02:00
// Create Bookshelf instance for this connection.
const ORM = new bookshelf(strapi.connections[connectionName]);
try {
// Require `config/functions/bookshelf.js` file to customize connection.
require(path.resolve(
strapi.config.appPath,
'config',
'functions',
'bookshelf.js'
))(ORM, strapi.connections[connectionName]);
} catch (err) {
// This is not an error if the file is not found.
2016-03-18 11:12:50 +01:00
}
2017-07-24 19:58:03 +02:00
// Load plugins
if (_.get(connection, 'options.plugins', true) !== false) {
2017-07-24 19:58:03 +02:00
ORM.plugin('visibility');
ORM.plugin('pagination');
}
2017-11-15 17:27:07 +01:00
const mountModels = (models, target, plugin = false) => {
2017-11-15 16:59:12 +01:00
// Parse every registered model.
_.forEach(models, (definition, model) => {
definition.globalName = _.upperFirst(_.camelCase(definition.globalId));
2017-11-15 16:59:12 +01:00
_.defaults(definition, {
primaryKey: 'id'
});
// Define local GLOBALS to expose every models in this file.
GLOBALS[definition.globalId] = {};
// Add some informations about ORM & client connection & tableName
2017-11-15 16:59:12 +01:00
definition.orm = 'bookshelf';
definition.client = _.get(connection.settings, 'client');
// Register the final model for Bookshelf.
const loadedModel = _.assign({
2017-11-15 16:59:12 +01:00
tableName: definition.collectionName,
hasTimestamps: _.get(definition, 'options.timestamps') === true,
idAttribute: _.get(definition, 'options.idAttribute', 'id'),
associations: []
}, definition.options);
2017-11-15 16:59:12 +01:00
if (_.isString(_.get(connection, 'options.pivot_prefix'))) {
loadedModel.toJSON = function(options = {}) {
const { shallow = false, omitPivot = false } = options;
const attributes = this.serialize(options);
2016-03-18 11:12:50 +01:00
2017-11-15 16:59:12 +01:00
if (!shallow) {
const pivot = this.pivot && !omitPivot && this.pivot.attributes;
2017-11-15 16:59:12 +01:00
// Remove pivot attributes with prefix.
_.keys(pivot).forEach(key => delete attributes[`${PIVOT_PREFIX}${key}`]);
2017-07-24 19:58:03 +02:00
2017-11-15 16:59:12 +01:00
// Add pivot attributes without prefix.
const pivotAttributes = _.mapKeys(pivot, (value, key) => `${connection.options.pivot_prefix}${key}`);
2016-03-18 11:12:50 +01:00
2017-11-15 16:59:12 +01:00
return Object.assign({}, attributes, pivotAttributes);
}
2017-11-15 16:59:12 +01:00
return attributes;
};
}
2017-11-15 16:59:12 +01:00
// Initialize the global variable with the
// capitalized model name.
2017-11-15 17:27:07 +01:00
if (!plugin) {
global[definition.globalName] = {};
2017-11-15 17:27:07 +01:00
}
2017-11-15 16:59:12 +01:00
// Call this callback function after we are done parsing
// all attributes for relationships-- see below.
const done = _.after(_.size(definition.attributes), () => {
try {
// External function to map key that has been updated with `columnName`
const mapper = (params = {}) =>
_.mapKeys(params, (value, key) => {
const attr = definition.attributes[key] || {};
return _.isPlainObject(attr) &&
_.isString(attr['columnName'])
? attr['columnName']
: key;
});
// Update serialize to reformat data for polymorphic associations.
loadedModel.serialize = function(options) {
const attrs = _.clone(this.attributes);
if (options && options.shallow) {
return attrs;
}
const relations = this.relations;
definition.associations
.filter(association => association.nature.toLowerCase().indexOf('morph') !== -1)
.map(association => {
// Retrieve relation Bookshelf object.
const relation = relations[association.alias];
if (relation) {
// Extract raw JSON data.
attrs[association.alias] = relation.toJSON ? relation.toJSON(options) : relation;
// Retrieve opposite model.
const model = association.plugin ?
strapi.plugins[association.plugin].models[association.collection || association.model]:
strapi.models[association.collection || association.model];
// Reformat data by bypassing the many-to-many relationship.
switch (association.nature) {
2018-02-22 15:34:33 +01:00
case 'oneToManyMorph':
attrs[association.alias] = attrs[association.alias][model.collectionName];
break;
2018-02-22 15:34:33 +01:00
case 'manyToManyMorph':
attrs[association.alias] = attrs[association.alias].map(rel => rel[model.collectionName]);
break;
2018-02-22 15:34:33 +01:00
case 'oneMorphToOne':
attrs[association.alias] = attrs[association.alias].related;
break;
2018-02-22 15:34:33 +01:00
case 'manyMorphToOne':
attrs[association.alias] = attrs[association.alias].map(obj => obj.related);
break;
default:
}
}
});
return attrs;
}
2017-11-15 16:59:12 +01:00
// Initialize lifecycle callbacks.
loadedModel.initialize = function() {
const lifecycle = {
creating: 'beforeCreate',
created: 'afterCreate',
destroying: 'beforeDestroy',
destroyed: 'afterDestroy',
updating: 'beforeUpdate',
updated: 'afterUpdate',
fetching: 'beforeFetch',
'fetching:collection': 'beforeFetchCollection',
fetched: 'afterFetch',
'fetched:collection': 'afterFetchCollection',
saving: 'beforeSave',
saved: 'afterSave'
};
_.forEach(lifecycle, (fn, key) => {
if (_.isFunction(target[model.toLowerCase()][fn])) {
this.on(key, target[model.toLowerCase()][fn]);
}
});
// Update withRelated level to bypass many-to-many association for polymorphic relationshiips.
// Apply only during fetching.
this.on('fetching:collection', (instance, attrs, options) => {
if (_.isArray(options.withRelated)) {
options.withRelated = options.withRelated.map(path => {
const association = definition.associations
.filter(association => association.nature.toLowerCase().indexOf('morph') !== -1)
.filter(association => association.alias === path || association.via === path)[0];
if (association) {
// Override on polymorphic path only.
if (_.isString(path) && path === association.via) {
return `related.${association.via}`;
} else if (_.isString(path) && path === association.alias) {
// MorphTo side.
if (association.related) {
return `${association.alias}.related`;
}
// oneToMorph or manyToMorph side.
// Retrieve collection name because we are using it to build our hidden model.
const model = association.plugin ?
strapi.plugins[association.plugin].models[association.collection || association.model]:
strapi.models[association.collection || association.model];
return `${association.alias}.${model.collectionName}`;
}
}
return path;
});
}
return _.isFunction(
target[model.toLowerCase()]['beforeFetchCollection']
)
? target[model.toLowerCase()]['beforeFetchCollection']
: Promise.resolve();
});
2017-11-15 16:59:12 +01:00
this.on('saving', (instance, attrs, options) => {
instance.attributes = mapper(instance.attributes);
attrs = mapper(attrs);
return _.isFunction(
2017-11-15 17:27:07 +01:00
target[model.toLowerCase()]['beforeSave']
2017-11-15 16:59:12 +01:00
)
2017-11-15 17:27:07 +01:00
? target[model.toLowerCase()]['beforeSave']
2017-11-15 16:59:12 +01:00
: Promise.resolve();
});
};
2017-07-24 19:58:03 +02:00
2017-11-15 16:59:12 +01:00
loadedModel.hidden = _.keys(
_.keyBy(
_.filter(definition.attributes, (value, key) => {
if (
value.hasOwnProperty('columnName') &&
!_.isEmpty(value.columnName) &&
value.columnName !== key
) {
return true;
}
}),
'columnName'
2017-07-24 19:58:03 +02:00
)
2017-11-15 16:59:12 +01:00
);
2017-07-24 19:58:03 +02:00
GLOBALS[definition.globalId] = ORM.Model.extend(loadedModel);
if (!plugin) {
// Only expose as real global variable the models which
// are not scoped in a plugin.
global[definition.globalId] = GLOBALS[definition.globalId];
2017-11-15 17:27:07 +01:00
}
// Expose ORM functions through the `strapi.models[xxx]`
// or `strapi.plugins[xxx].models[yyy]` object.
target[model] = _.assign(GLOBALS[definition.globalId], target[model]);
2017-11-15 16:59:12 +01:00
// Push attributes to be aware of model schema.
2017-11-15 17:27:07 +01:00
target[model]._attributes = definition.attributes;
2017-02-15 14:43:09 +01:00
2017-11-15 16:59:12 +01:00
} catch (err) {
strapi.log.error('Impossible to register the `' + model + '` model.');
2017-11-15 16:59:12 +01:00
strapi.log.error(err);
strapi.stop();
}
});
2017-02-15 14:43:09 +01:00
2017-11-15 16:59:12 +01:00
if (_.isEmpty(definition.attributes)) {
done();
2017-07-24 19:58:03 +02:00
}
2017-02-15 14:43:09 +01:00
2017-11-15 16:59:12 +01:00
// Add every relationships to the loaded model for Bookshelf.
// Basic attributes don't need this-- only relations.
_.forEach(definition.attributes, (details, name) => {
const verbose = _.get(
utilsModels.getNature(details, name, undefined, model.toLowerCase()),
'verbose'
) || '';
// Build associations key
utilsModels.defineAssociations(
model.toLowerCase(),
2017-11-15 16:59:12 +01:00
definition,
details,
name
);
2017-02-15 14:43:09 +01:00
2018-02-22 15:34:33 +01:00
let globalId;
const globalName = details.model || details.collection || '';
// Exclude polymorphic association.
if (globalName !== '*') {
globalId = details.plugin ?
_.get(strapi.plugins,`${details.plugin}.models.${globalName.toLowerCase()}.globalId`):
_.get(strapi.models, `${globalName.toLowerCase()}.globalId`);
}
2017-11-15 16:59:12 +01:00
switch (verbose) {
case 'hasOne': {
const FK = details.plugin ?
_.findKey(
strapi.plugins[details.plugin].models[details.model].attributes,
details => {
if (
details.hasOwnProperty('model') &&
details.model === model &&
details.hasOwnProperty('via') &&
details.via === name
) {
return details;
}
2017-11-15 16:59:12 +01:00
}
):
_.findKey(
strapi.models[details.model].attributes,
details => {
if (
details.hasOwnProperty('model') &&
details.model === model &&
details.hasOwnProperty('via') &&
details.via === name
) {
return details;
}
}
);
const columnName = details.plugin ?
_.get(strapi.plugins, `${details.plugin}.models.${details.model}.attributes.${FK}.columnName`, FK):
_.get(strapi.models, `${details.model}.attributes.${FK}.columnName`, FK);
2017-11-15 16:59:12 +01:00
loadedModel[name] = function() {
return this.hasOne(
GLOBALS[globalId],
columnName
2017-11-15 16:59:12 +01:00
);
};
break;
}
case 'hasMany': {
const columnName = details.plugin ?
_.get(strapi.plugins, `${details.plugin}.models.${globalId.toLowerCase()}.attributes.${details.via}.columnName`, details.via):
_.get(strapi.models[globalId.toLowerCase()].attributes, `${details.via}.columnName`, details.via);
2017-11-15 16:59:12 +01:00
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
loadedModel[name] = function() {
return this.hasMany(GLOBALS[globalId], columnName);
2017-11-15 16:59:12 +01:00
};
break;
}
case 'belongsTo': {
loadedModel[name] = function() {
return this.belongsTo(
GLOBALS[globalId],
_.get(details, 'columnName', name)
2017-11-15 16:59:12 +01:00
);
};
break;
}
case 'belongsToMany': {
const collection = details.plugin ?
strapi.plugins[details.plugin].models[details.collection]:
strapi.models[details.collection];
2017-11-15 16:59:12 +01:00
const collectionName = _.get(details, 'collectionName') ||
_.map(
_.sortBy(
[
collection.attributes[
2017-11-15 16:59:12 +01:00
details.via
],
details
2017-07-24 19:58:03 +02:00
],
2017-11-15 16:59:12 +01:00
'collection'
),
table => {
return _.snakeCase(
pluralize.plural(table.collection) +
' ' +
pluralize.plural(table.via)
);
}
).join('__');
const relationship = _.clone(
collection.attributes[details.via]
2017-11-15 16:59:12 +01:00
);
2017-11-15 16:59:12 +01:00
// Force singular foreign key
relationship.attribute = pluralize.singular(
relationship.collection
);
details.attribute = pluralize.singular(details.collection);
2017-11-15 16:59:12 +01:00
// Define PK column
details.column = utils.getPK(model, strapi.models);
relationship.column = utils.getPK(
details.collection,
strapi.models
);
2017-11-15 16:59:12 +01:00
// Sometimes the many-to-many relationships
// is on the same keys on the same models (ex: `friends` key in model `User`)
if (
details.attribute + '_' + details.column ===
relationship.attribute + '_' + relationship.column
) {
relationship.attribute = pluralize.singular(details.via);
}
2017-11-15 16:59:12 +01:00
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
2017-11-15 16:59:12 +01:00
loadedModel[name] = function() {
if (
_.isArray(_.get(details, 'withPivot')) &&
!_.isEmpty(details.withPivot)
) {
return this.belongsToMany(
GLOBALS[globalId],
2017-11-15 16:59:12 +01:00
collectionName,
relationship.attribute + '_' + relationship.column,
details.attribute + '_' + details.column
).withPivot(details.withPivot);
}
return this.belongsToMany(
GLOBALS[globalId],
collectionName,
relationship.attribute + '_' + relationship.column,
details.attribute + '_' + details.column
2017-11-15 16:59:12 +01:00
);
};
break;
}
case 'morphOne': {
const model = details.plugin ?
strapi.plugins[details.plugin].models[details.model]:
strapi.models[details.model];
const globalId = `${model.collectionName}_morph`;
loadedModel[name] = function() {
return this
.morphOne(GLOBALS[globalId], details.via, `${definition.collectionName}`)
.query(qb => {
qb.where(_.get(model, `attributes.${details.via}.filter`, 'field'), name);
});
}
break;
}
case 'morphMany': {
const collection = details.plugin ?
strapi.plugins[details.plugin].models[details.collection]:
strapi.models[details.collection];
const globalId = `${collection.collectionName}_morph`;
loadedModel[name] = function() {
return this
.morphMany(GLOBALS[globalId], details.via, `${definition.collectionName}`)
.query(qb => {
qb.where(_.get(collection, `attributes.${details.via}.filter`, 'field'), name);
});
}
break;
}
case 'belongsToMorph':
case 'belongsToManyMorph': {
const association = definition.associations
.find(association => association.alias === name);
const morphValues = association.related.map(id => {
let models = Object.values(strapi.models).filter(model => model.globalId === id);
if (models.length === 0) {
models = Object.keys(strapi.plugins).reduce((acc, current) => {
const models = Object.values(strapi.plugins[current].models).filter(model => model.globalId === id);
if (acc.length === 0 && models.length > 0) {
acc = models;
}
return acc;
}, []);
}
if (models.length === 0) {
strapi.log.error('Impossible to register the `' + model + '` model.');
strapi.log.error('The collection name cannot be found for the morphTo method.');
strapi.stop();
}
return models[0].collectionName;
});
// Define new model.
const options = {
tableName: `${definition.collectionName}_morph`,
[definition.collectionName]: function () {
return this
.belongsTo(
GLOBALS[definition.globalId],
`${definition.collectionName}_id`
);
},
related: function () {
return this
.morphTo(name, ...association.related.map((id, index) => [GLOBALS[id], morphValues[index]]));
}
};
GLOBALS[options.tableName] = ORM.Model.extend(options);
// Hack Bookshelf to create a many-to-many polymorphic association.
// Upload has many Upload_morph that morph to different model.
loadedModel[name] = function () {
if (verbose === 'belongsToMorph') {
return this.hasOne(
GLOBALS[options.tableName],
`${definition.collectionName}_id`
);
}
return this.hasMany(
GLOBALS[options.tableName],
`${definition.collectionName}_id`
);
};
break;
}
2017-11-15 16:59:12 +01:00
default: {
break;
}
2017-07-24 19:58:03 +02:00
}
2016-03-18 11:12:50 +01:00
2017-11-15 16:59:12 +01:00
done();
});
2016-03-18 11:12:50 +01:00
});
2017-11-15 16:59:12 +01:00
};
// Mount `./api` models.
mountModels(_.pickBy(strapi.models, { connection: connectionName }), strapi.models);
2017-11-28 15:00:49 +01:00
// Mount `./plugins` models.
_.forEach(strapi.plugins, (plugin, name) => {
mountModels(_.pickBy(strapi.plugins[name].models, { connection: connectionName }), plugin.models, name);
2017-11-15 17:27:07 +01:00
});
2016-03-18 11:12:50 +01:00
});
2018-01-24 20:15:11 +05:30
cb();
2017-09-13 12:18:54 +02:00
},
getQueryParams: (value, type, key) => {
const result = {};
switch (type) {
case '=':
result.key = `where.${key}[0]`;
result.value = {
symbol: '=',
value
};
break;
case '_ne':
result.key = `where.${key}[0]`;
result.value = {
symbol: '!=',
value
};
break;
case '_lt':
result.key = `where.${key}[0]`;
result.value = {
symbol: '<',
value
};
break;
case '_gt':
result.key = `where.${key}[0]`;
result.value = {
symbol: '>',
value
};
break;
case '_lte':
result.key = `where.${key}[0]`;
result.value = {
symbol: '<=',
value
};
break;
case '_gte':
result.key = `where.${key}[0]`;
result.value = {
symbol: '>=',
value
};
break;
case '_sort':
result.key = `sort`;
result.value = (_.toLower(value) === 'desc') ? '-' : '';
2017-09-13 12:18:54 +02:00
result.value += key;
break;
case '_start':
result.key = `start`;
result.value = parseFloat(value);
break;
case '_limit':
result.key = `limit`;
result.value = parseFloat(value);
break;
default:
return undefined;
2017-09-13 12:18:54 +02:00
}
return result;
},
2017-11-01 15:16:28 +01:00
manageRelations: async function (model, params) {
const models = strapi.models;
const Model = strapi.models[model];
const virtualFields = [];
const record = await Model
.forge({
[Model.primaryKey]: params[Model.primaryKey]
})
.fetch({
withRelated: Model.associations.map(x => x.alias)
});
const response = record ? record.toJSON() : record;
// Only update fields which are on this document.
const values = params.parseRelationships === false ? params.values : Object.keys(JSON.parse(JSON.stringify(params.values))).reduce((acc, current) => {
const association = Model.associations.filter(x => x.alias === current)[0];
const details = Model._attributes[current];
if (_.get(Model._attributes, `${current}.isVirtual`) !== true && _.isUndefined(association)) {
acc[current] = params.values[current];
} else {
switch (association.nature) {
case 'oneToOne':
if (response[current] !== params.values[current]) {
const value = _.isNull(params.values[current]) ? response[current] : params.values;
2017-10-31 14:44:34 +01:00
const recordId = _.isNull(params.values[current]) ? value[Model.primaryKey] || value.id || value._id : typeof value[current] === 'object' ? value[current].id : value[current];
if (response[current] && _.isObject(response[current]) && response[current][Model.primaryKey] !== value[current]) {
virtualFields.push(
2017-11-01 15:16:28 +01:00
this.manageRelations(details.collection || details.model, {
id: response[current][Model.primaryKey],
values: {
[details.via]: null
},
parseRelationships: false
})
);
}
// Remove previous relationship asynchronously if it exists.
virtualFields.push(
2017-10-27 19:06:22 +02:00
models[details.model || details.collection]
.forge({ id : recordId })
.fetch({
withRelated: models[details.model || details.collection].associations.map(x => x.alias)
})
.then(response => {
const record = response ? response.toJSON() : response;
if (record && _.isObject(record[details.via]) && record[details.via][current] !== value[current]) {
2017-11-01 15:16:28 +01:00
return this.manageRelations(model, {
2017-10-27 19:06:22 +02:00
id: record[details.via][models[details.model || details.collection].primaryKey] || record[details.via].id,
values: {
[current]: null
},
parseRelationships: false
});
}
return Promise.resolve();
})
);
// Update the record on the other side.
// When params.values[current] is null this means that we are removing the relation.
2017-11-01 15:16:28 +01:00
virtualFields.push(this.manageRelations(details.model || details.collection, {
id: recordId,
values: {
2017-10-31 13:43:48 +01:00
[details.via]: _.isNull(params.values[current]) ? null : value[Model.primaryKey] || params.id || params._id || value.id || value._id
},
parseRelationships: false
}));
2017-10-31 14:44:34 +01:00
acc[current] = _.isNull(params.values[current]) ? null : typeof value[current] === 'object' ? value[current][Model.primaryKey] : value[current];
}
break;
case 'oneToMany':
case 'manyToOne':
case 'manyToMany':
if (details.dominant === true) {
acc[current] = params.values[current];
} else if (response[current] && _.isArray(response[current]) && current !== 'id') {
// Records to add in the relation.
const toAdd = _.differenceWith(params.values[current], response[current], (a, b) =>
((typeof a === 'number') ? a : a[Model.primaryKey].toString()) === b[Model.primaryKey].toString()
);
// Records to remove in the relation.
const toRemove = _.differenceWith(response[current], params.values[current], (a, b) =>
a[Model.primaryKey].toString() === ((typeof b === 'number') ? b : b[Model.primaryKey].toString())
)
.filter(x => toAdd.find(y => x.id === y.id) === undefined);
// Push the work into the flow process.
toAdd.forEach(value => {
value = (typeof value === 'number') ? { id: value } : value;
value[details.via] = parseFloat(params[Model.primaryKey]);
params.values[Model.primaryKey] = parseFloat(params[Model.primaryKey]);
2017-11-01 15:16:28 +01:00
virtualFields.push(this.addRelation(details.model || details.collection, {
id: value[Model.primaryKey] || value.id || value._id,
values: association.nature === 'manyToMany' ? params.values : value,
foreignKey: current
}));
});
toRemove.forEach(value => {
value[details.via] = null;
2017-11-01 15:16:28 +01:00
virtualFields.push(this.removeRelation(details.model || details.collection, {
id: value[Model.primaryKey] || value.id || value._id,
values: association.nature === 'manyToMany' ? params.values : value,
foreignKey: current
}));
});
} else if (_.get(Model._attributes, `${current}.isVirtual`) !== true) {
acc[current] = params.values[current];
}
break;
default:
}
}
return acc;
}, {});
if (!_.isEmpty(values)) {
virtualFields.push(Model
.forge({
[Model.primaryKey]: params[Model.primaryKey]
})
.save(values, {
patch: true
}));
} else {
virtualFields.push(Promise.resolve(_.assign(response, params.values)));
}
// Update virtuals fields.
2017-11-02 13:57:52 +01:00
await Promise.all(virtualFields);
},
2017-11-01 15:16:28 +01:00
addRelation: async function (model, params) {
const Model = strapi.models[model];
const association = Model.associations.filter(x => x.via === params.foreignKey)[0];
if (!association) {
// Resolve silently.
return Promise.resolve();
}
switch (association.nature) {
case 'oneToOne':
case 'oneToMany':
return this.manageRelations(model, params);
case 'manyToMany':
return Model.forge({
[Model.primaryKey]: parseFloat(params[Model.primaryKey])
})[association.alias]().attach(params.values[Model.primaryKey]);
default:
// Resolve silently.
return Promise.resolve();
}
},
2017-11-01 15:16:28 +01:00
removeRelation: async function (model, params) {
const Model = strapi.models[model];
const association = Model.associations.filter(x => x.via === params.foreignKey)[0];
if (!association) {
// Resolve silently.
return Promise.resolve();
}
switch (association.nature) {
case 'oneToOne':
case 'oneToMany':
return this.manageRelations(model, params);
case 'manyToMany':
return Model.forge({
[Model.primaryKey]: parseFloat(params[Model.primaryKey])
})[association.alias]().detach(params.values[Model.primaryKey]);
default:
// Resolve silently.
return Promise.resolve();
}
2016-03-18 11:12:50 +01:00
}
};
return hook;
};