993 lines
36 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');
2018-05-21 17:22:25 +07:00
// Strapi helpers for models.
const utilsModels = require('strapi-utils').models;
2018-05-04 17:29:44 +02:00
// Local helpers.
const utils = require('./utils/');
2018-05-16 18:17:13 +02:00
const relations = require('./relations');
2019-03-13 19:27:18 +01:00
const buildQuery = require('./buildQuery');
2019-04-19 17:24:56 +02:00
const buildDatabaseSchema = require('./buildDatabaseSchema');
2018-05-04 17:29:44 +02:00
2017-02-15 14:43:09 +01:00
const PIVOT_PREFIX = '_pivot_';
const GLOBALS = {};
2017-02-15 14:43:09 +01:00
const getDatabaseName = connection => {
const dbName = _.get(connection.settings, 'database');
switch (_.get(connection.settings, 'client')) {
case 'sqlite3':
return 'main';
case 'pg':
return `${dbName}.public`;
case 'mysql':
return dbName;
default:
return dbName;
}
};
2016-03-18 11:12:50 +01:00
/**
* Bookshelf hook
*/
module.exports = function(strapi) {
const hook = _.merge(
{
/**
* Default options
*/
defaults: {
defaultConnection: 'default',
host: 'localhost',
},
/**
* Initialize the hook
*/
initialize: async cb => {
const connections = _.pickBy(strapi.config.connections, {
connector: 'strapi-hook-bookshelf',
});
2016-03-18 11:12:50 +01:00
2019-04-19 17:24:56 +02:00
const databaseUpdates = [];
_.forEach(connections, (connection, connectionName) => {
// Apply defaults
2019-04-09 16:01:01 +02:00
_.defaults(
connection.settings,
2019-04-19 17:24:56 +02:00
strapi.config.hook.settings.bookshelf
2019-04-09 16:01:01 +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.
2019-04-09 16:01:01 +02:00
require(path.resolve(
strapi.config.appPath,
'config',
'functions',
2019-04-19 17:24:56 +02:00
'bookshelf.js'
2019-04-09 16:01:01 +02:00
))(ORM, connection);
} catch (err) {
// This is not an error if the file is not found.
}
// Load plugins
if (_.get(connection, 'options.plugins', true) !== false) {
ORM.plugin('visibility');
ORM.plugin('pagination');
}
const mountModels = (models, target, plugin = false) => {
// Parse every authenticated model.
_.forEach(models, (definition, model) => {
2019-04-19 17:24:56 +02:00
definition.globalName = _.upperFirst(
_.camelCase(definition.globalId)
);
2019-04-09 15:29:17 +02:00
definition.associations = [];
// Define local GLOBALS to expose every models in this file.
GLOBALS[definition.globalId] = {};
// Add some informations about ORM & client connection & tableName
definition.orm = 'bookshelf';
definition.databaseName = getDatabaseName(connection);
definition.client = _.get(connection.settings, 'client');
_.defaults(definition, {
primaryKey: 'id',
2019-04-09 16:01:01 +02:00
primaryKeyType: _.get(
definition,
'options.idAttributeType',
2019-04-19 17:24:56 +02:00
'integer'
2019-04-09 16:01:01 +02:00
),
});
// Use default timestamp column names if value is `true`
if (_.get(definition, 'options.timestamps', false) === true) {
2019-04-09 16:01:01 +02:00
_.set(definition, 'options.timestamps', [
'created_at',
'updated_at',
]);
}
// Use false for values other than `Boolean` or `Array`
if (
!_.isArray(_.get(definition, 'options.timestamps')) &&
!_.isBoolean(_.get(definition, 'options.timestamps'))
) {
_.set(definition, 'options.timestamps', false);
}
2016-03-18 11:12:50 +01:00
// Register the final model for Bookshelf.
const loadedModel = _.assign(
{
tableName: definition.collectionName,
hasTimestamps: _.get(definition, 'options.timestamps', false),
idAttribute: _.get(definition, 'options.idAttribute', 'id'),
associations: [],
2019-04-09 16:01:01 +02:00
defaults: Object.keys(definition.attributes).reduce(
(acc, current) => {
if (
definition.attributes[current].type &&
definition.attributes[current].default
) {
acc[current] = definition.attributes[current].default;
}
2017-07-24 19:58:03 +02:00
2019-04-09 16:01:01 +02:00
return acc;
},
2019-04-19 17:24:56 +02:00
{}
2019-04-09 16:01:01 +02:00
),
},
2019-04-19 17:24:56 +02:00
definition.options
);
if (_.isString(_.get(connection, 'options.pivot_prefix'))) {
loadedModel.toJSON = function(options = {}) {
const { shallow = false, omitPivot = false } = options;
const attributes = this.serialize(options);
2017-07-24 19:58:03 +02:00
if (!shallow) {
2019-04-09 16:01:01 +02:00
const pivot =
this.pivot && !omitPivot && this.pivot.attributes;
2017-07-24 19:58:03 +02:00
// Remove pivot attributes with prefix.
2019-04-09 16:01:01 +02:00
_.keys(pivot).forEach(
2019-04-19 17:24:56 +02:00
key => delete attributes[`${PIVOT_PREFIX}${key}`]
2019-04-09 16:01:01 +02:00
);
2016-03-18 11:12:50 +01:00
// Add pivot attributes without prefix.
const pivotAttributes = _.mapKeys(
pivot,
2019-04-19 17:24:56 +02:00
(value, key) => `${connection.options.pivot_prefix}${key}`
);
2017-07-24 19:58:03 +02:00
return Object.assign({}, attributes, pivotAttributes);
}
2017-11-15 16:59:12 +01:00
return attributes;
};
}
// Initialize the global variable with the
// capitalized model name.
if (!plugin) {
global[definition.globalName] = {};
}
2019-01-23 15:19:34 +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 = {}) => {
2019-04-09 16:01:01 +02:00
if (
definition.client === 'mysql' ||
definition.client === 'sqlite3'
) {
Object.keys(params).map(key => {
const attr = definition.attributes[key] || {};
2018-04-06 17:49:08 +02:00
if (attr.type === 'json') {
params[key] = JSON.stringify(params[key]);
}
});
}
2019-01-23 15:19:34 +01:00
return _.mapKeys(params, (value, key) => {
const attr = definition.attributes[key] || {};
2016-03-18 11:12:50 +01:00
2019-04-09 16:01:01 +02:00
return _.isPlainObject(attr) &&
_.isString(attr['columnName'])
2019-03-13 19:27:18 +01:00
? attr['columnName']
: key;
});
};
// Update serialize to reformat data for polymorphic associations.
loadedModel.serialize = function(options) {
const attrs = _.clone(this.attributes);
2017-07-24 19:58:03 +02:00
if (options && options.shallow) {
return attrs;
}
2016-03-18 11:12:50 +01:00
const relations = this.relations;
// Extract association except polymorphic.
const associations = definition.associations.filter(
2019-04-09 16:01:01 +02:00
association =>
2019-04-19 17:24:56 +02:00
association.nature.toLowerCase().indexOf('morph') === -1
);
// Extract polymorphic association.
const polymorphicAssociations = definition.associations.filter(
2019-04-09 16:01:01 +02:00
association =>
2019-04-19 17:24:56 +02:00
association.nature.toLowerCase().indexOf('morph') !== -1
);
polymorphicAssociations.map(association => {
// Retrieve relation Bookshelf object.
const relation = relations[association.alias];
if (relation) {
// Extract raw JSON data.
2019-03-13 19:27:18 +01:00
attrs[association.alias] = relation.toJSON
? relation.toJSON(options)
: relation;
2018-06-20 20:47:45 +02:00
// Retrieve opposite model.
const model = association.plugin
2019-03-13 19:27:18 +01:00
? strapi.plugins[association.plugin].models[
2019-04-09 16:01:01 +02:00
association.collection || association.model
]
: strapi.models[
association.collection || association.model
];
// Reformat data by bypassing the many-to-many relationship.
switch (association.nature) {
case 'oneToManyMorph':
2019-03-13 19:27:18 +01:00
attrs[association.alias] =
attrs[association.alias][model.collectionName];
break;
case 'manyToManyMorph':
2019-04-09 16:01:01 +02:00
attrs[association.alias] = attrs[
association.alias
].map(rel => rel[model.collectionName]);
break;
case 'oneMorphToOne':
2019-04-09 16:01:01 +02:00
attrs[association.alias] =
attrs[association.alias].related;
break;
case 'manyMorphToOne':
case 'manyMorphToMany':
2019-04-09 16:01:01 +02:00
attrs[association.alias] = attrs[
association.alias
].map(obj => obj.related);
break;
default:
}
2018-06-20 20:47:45 +02:00
}
});
2017-11-15 16:59:12 +01:00
associations.map(association => {
const relation = relations[association.alias];
2017-11-15 16:59:12 +01:00
if (relation) {
// Extract raw JSON data.
2019-03-13 19:27:18 +01:00
attrs[association.alias] = relation.toJSON
? relation.toJSON(options)
: relation;
}
});
return attrs;
};
// Initialize lifecycle callbacks.
loadedModel.initialize = function() {
const lifecycle = {
creating: 'beforeCreate',
created: 'afterCreate',
destroying: 'beforeDestroy',
destroyed: 'afterDestroy',
updating: 'beforeUpdate',
updated: 'afterUpdate',
fetching: 'beforeFetch',
'fetching:collection': 'beforeFetchAll',
fetched: 'afterFetch',
'fetched:collection': 'afterFetchAll',
saving: 'beforeSave',
saved: 'afterSave',
};
_.forEach(lifecycle, (fn, key) => {
if (_.isFunction(target[model.toLowerCase()][fn])) {
this.on(key, target[model.toLowerCase()][fn]);
}
});
const findModelByAssoc = ({ assoc }) => {
return assoc.plugin
2019-04-09 16:01:01 +02:00
? strapi.plugins[assoc.plugin].models[
assoc.collection || assoc.model
]
: strapi.models[assoc.collection || assoc.model];
};
const isPolymorphic = ({ assoc }) => {
return assoc.nature.toLowerCase().indexOf('morph') !== -1;
};
2019-04-09 16:01:01 +02:00
const formatPolymorphicPopulate = ({
assoc,
path,
prefix = '',
}) => {
if (_.isString(path) && path === assoc.via) {
return `related.${assoc.via}`;
} else if (_.isString(path) && path === assoc.alias) {
// MorphTo side.
if (assoc.related) {
return `${prefix}${assoc.alias}.related`;
}
// oneToMorph or manyToMorph side.
// Retrieve collection name because we are using it to build our hidden model.
const model = findModelByAssoc({ assoc });
2017-11-15 16:59:12 +01:00
return {
2019-04-09 16:01:01 +02:00
[`${prefix}${assoc.alias}.${
model.collectionName
}`]: function(query) {
query.orderBy('created_at', 'desc');
},
};
}
};
// Update withRelated level to bypass many-to-many association for polymorphic relationshiips.
// Apply only during fetching.
2019-04-09 16:01:01 +02:00
this.on(
'fetching fetching:collection',
(instance, attrs, options) => {
if (_.isArray(options.withRelated)) {
options.withRelated = options.withRelated
.map(path => {
const assoc = definition.associations.find(
assoc =>
2019-04-19 17:24:56 +02:00
assoc.alias === path || assoc.via === path
2019-04-09 16:01:01 +02:00
);
2019-04-09 16:01:01 +02:00
if (assoc && isPolymorphic({ assoc })) {
return formatPolymorphicPopulate({
assoc,
path,
});
}
2019-04-09 16:01:01 +02:00
let extraAssocs = [];
if (assoc) {
const assocModel = findModelByAssoc({ assoc });
extraAssocs = assocModel.associations
.filter(assoc => isPolymorphic({ assoc }))
.map(assoc =>
formatPolymorphicPopulate({
assoc,
path: assoc.alias,
prefix: `${path}.`,
2019-04-19 17:24:56 +02:00
})
2019-04-09 16:01:01 +02:00
);
}
2019-04-09 16:01:01 +02:00
return [path, ...extraAssocs];
})
.reduce((acc, paths) => acc.concat(paths), []);
}
2019-04-09 16:01:01 +02:00
return _.isFunction(
2019-04-19 17:24:56 +02:00
target[model.toLowerCase()]['beforeFetchAll']
2019-04-09 16:01:01 +02:00
)
? target[model.toLowerCase()]['beforeFetchAll']
: Promise.resolve();
2019-04-19 17:24:56 +02:00
}
2019-04-09 16:01:01 +02:00
);
2017-11-15 16:59:12 +01:00
2019-03-13 19:27:18 +01:00
//eslint-disable-next-line
this.on('saving', (instance, attrs, options) => {
instance.attributes = mapper(instance.attributes);
attrs = mapper(attrs);
2019-04-09 16:01:01 +02:00
return _.isFunction(
2019-04-19 17:24:56 +02:00
target[model.toLowerCase()]['beforeSave']
2019-04-09 16:01:01 +02:00
)
? target[model.toLowerCase()]['beforeSave']
: Promise.resolve();
});
// Convert to JSON format stringify json for mysql database
2019-04-09 16:01:01 +02:00
if (
definition.client === 'mysql' ||
definition.client === 'sqlite3'
) {
const events = [
{
name: 'saved',
target: 'afterSave',
},
{
name: 'fetched',
target: 'afterFetch',
},
{
name: 'fetched:collection',
target: 'afterFetchAll',
},
];
const jsonFormatter = attributes => {
Object.keys(attributes).map(key => {
const attr = definition.attributes[key] || {};
if (attr.type === 'json') {
attributes[key] = JSON.parse(attributes[key]);
}
});
};
events.forEach(event => {
let fn;
2018-06-20 16:21:09 +02:00
if (event.name.indexOf('collection') !== -1) {
fn = instance =>
instance.models.map(entry => {
jsonFormatter(entry.attributes);
});
} else {
fn = instance => jsonFormatter(instance.attributes);
2018-06-20 16:21:09 +02:00
}
this.on(event.name, instance => {
fn(instance);
2018-06-26 14:18:31 +02:00
2019-04-09 16:01:01 +02:00
return _.isFunction(
2019-04-19 17:24:56 +02:00
target[model.toLowerCase()][event.target]
2019-04-09 16:01:01 +02:00
)
? target[model.toLowerCase()][event.target]
: Promise.resolve();
2018-06-26 14:18:31 +02:00
});
2018-06-20 16:21:09 +02:00
});
}
};
2017-07-24 19:58:03 +02:00
loadedModel.hidden = _.keys(
_.keyBy(
_.filter(definition.attributes, (value, key) => {
if (
value.hasOwnProperty('columnName') &&
!_.isEmpty(value.columnName) &&
value.columnName !== key
) {
return true;
}
}),
2019-04-19 17:24:56 +02:00
'columnName'
)
);
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];
}
2018-04-27 13:47:09 +02:00
// Expose ORM functions through the `strapi.models[xxx]`
// or `strapi.plugins[xxx].models[yyy]` object.
2019-04-09 16:01:01 +02:00
target[model] = _.assign(
GLOBALS[definition.globalId],
2019-04-19 17:24:56 +02:00
target[model]
2019-04-09 16:01:01 +02:00
);
// Push attributes to be aware of model schema.
target[model]._attributes = definition.attributes;
target[model].updateRelations = relations.update;
2019-04-19 17:24:56 +02:00
databaseUpdates.push(
buildDatabaseSchema({
ORM,
definition,
loadedModel,
connection,
model: target[model],
2019-04-19 17:24:56 +02:00
})
);
} catch (err) {
2019-04-09 16:01:01 +02:00
strapi.log.error(
2019-04-19 17:24:56 +02:00
`Impossible to register the '${model}' model.`
2019-04-09 16:01:01 +02:00
);
strapi.log.error(err);
strapi.stop();
}
});
// Add every relationships to the loaded model for Bookshelf.
// Basic attributes don't need this-- only relations.
_.forEach(definition.attributes, (details, name) => {
const verbose =
2019-03-13 19:27:18 +01:00
_.get(
2019-04-09 16:01:01 +02:00
utilsModels.getNature(
details,
name,
undefined,
2019-04-19 17:24:56 +02:00
model.toLowerCase()
2019-04-09 16:01:01 +02:00
),
2019-04-19 17:24:56 +02:00
'verbose'
2019-03-13 19:27:18 +01:00
) || '';
2017-02-15 14:43:09 +01:00
// Build associations key
2019-04-09 16:01:01 +02:00
utilsModels.defineAssociations(
model.toLowerCase(),
definition,
details,
2019-04-19 17:24:56 +02:00
name
2019-04-09 16:01:01 +02: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
2019-03-13 19:27:18 +01:00
? _.get(
2019-04-09 16:01:01 +02:00
strapi.plugins,
`${
details.plugin
2019-04-19 17:24:56 +02:00
}.models.${globalName.toLowerCase()}.globalId`
2019-04-09 16:01:01 +02:00
)
: _.get(
strapi.models,
2019-04-19 17:24:56 +02:00
`${globalName.toLowerCase()}.globalId`
2019-04-09 16:01:01 +02:00
);
}
switch (verbose) {
case 'hasOne': {
const FK = details.plugin
2019-03-13 19:27:18 +01:00
? _.findKey(
2019-04-09 16:01:01 +02:00
strapi.plugins[details.plugin].models[details.model]
.attributes,
details => {
if (
details.hasOwnProperty('model') &&
2019-03-13 19:27:18 +01:00
details.model === model &&
details.hasOwnProperty('via') &&
details.via === name
2019-04-09 16:01:01 +02:00
) {
return details;
}
2019-04-19 17:24:56 +02:00
}
2019-04-09 16:01:01 +02:00
)
: _.findKey(
strapi.models[details.model].attributes,
details => {
if (
details.hasOwnProperty('model') &&
details.model === model &&
details.hasOwnProperty('via') &&
details.via === name
) {
return details;
}
2019-04-19 17:24:56 +02:00
}
2019-04-09 16:01:01 +02:00
);
const columnName = details.plugin
? _.get(
strapi.plugins,
2019-04-09 16:01:01 +02:00
`${details.plugin}.models.${
details.model
}.attributes.${FK}.columnName`,
2019-04-19 17:24:56 +02:00
FK
)
2019-04-09 16:01:01 +02:00
: _.get(
strapi.models,
`${details.model}.attributes.${FK}.columnName`,
2019-04-19 17:24:56 +02:00
FK
2019-04-09 16:01:01 +02:00
);
2017-11-15 16:59:12 +01:00
loadedModel[name] = function() {
return this.hasOne(GLOBALS[globalId], columnName);
};
break;
}
case 'hasMany': {
const columnName = details.plugin
? _.get(
strapi.plugins,
2019-04-09 16:01:01 +02:00
`${
details.plugin
}.models.${globalId.toLowerCase()}.attributes.${
details.via
}.columnName`,
2019-04-19 17:24:56 +02:00
details.via
)
: _.get(
strapi.models[globalId.toLowerCase()].attributes,
`${details.via}.columnName`,
2019-04-19 17:24:56 +02:00
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);
};
break;
}
case 'belongsTo': {
loadedModel[name] = function() {
2019-04-09 16:01:01 +02:00
return this.belongsTo(
GLOBALS[globalId],
2019-04-19 17:24:56 +02:00
_.get(details, 'columnName', name)
2019-04-09 16:01:01 +02:00
);
};
break;
}
case 'belongsToMany': {
const collection = details.plugin
? strapi.plugins[details.plugin].models[
details.collection
]
: strapi.models[details.collection];
const collectionName =
_.get(details, 'collectionName') ||
2019-04-09 16:01:01 +02:00
utilsModels.getCollectionName(
collection.attributes[details.via],
2019-04-19 17:24:56 +02:00
details
2019-04-09 16:01:01 +02:00
);
2019-04-19 17:24:56 +02:00
const relationship = collection.attributes[details.via];
// Force singular foreign key
2019-04-09 16:01:01 +02:00
relationship.attribute = pluralize.singular(
2019-04-19 17:24:56 +02:00
relationship.collection
2019-04-09 16:01:01 +02:00
);
details.attribute = pluralize.singular(details.collection);
// Define PK column
details.column = utils.getPK(model, strapi.models);
2019-04-09 16:01:01 +02:00
relationship.column = utils.getPK(
details.collection,
2019-04-19 17:24:56 +02:00
strapi.models
2019-04-09 16:01:01 +02:00
);
// Sometimes the many-to-many relationships
// is on the same keys on the same models (ex: `friends` key in model `User`)
2017-11-15 16:59:12 +01:00
if (
2019-03-13 19:27:18 +01:00
`${details.attribute}_${details.column}` ===
`${relationship.attribute}_${relationship.column}`
2017-11-15 16:59:12 +01:00
) {
relationship.attribute = pluralize.singular(details.via);
}
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
loadedModel[name] = function() {
2019-04-09 16:01:01 +02:00
if (
_.isArray(_.get(details, 'withPivot')) &&
!_.isEmpty(details.withPivot)
) {
return this.belongsToMany(
GLOBALS[globalId],
collectionName,
`${relationship.attribute}_${relationship.column}`,
2019-04-19 17:24:56 +02:00
`${details.attribute}_${details.column}`
).withPivot(details.withPivot);
}
2017-11-15 16:59:12 +01:00
return this.belongsToMany(
GLOBALS[globalId],
2017-11-15 16:59:12 +01:00
collectionName,
2018-08-20 14:34:22 -05:00
`${relationship.attribute}_${relationship.column}`,
2019-04-19 17:24:56 +02:00
`${details.attribute}_${details.column}`
);
};
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() {
2019-03-13 19:27:18 +01:00
return this.morphOne(
GLOBALS[globalId],
details.via,
2019-04-19 17:24:56 +02:00
`${definition.collectionName}`
2019-03-13 19:27:18 +01:00
).query(qb => {
2019-04-09 16:01:01 +02:00
qb.where(
_.get(
model,
`attributes.${details.via}.filter`,
2019-04-19 17:24:56 +02:00
'field'
2019-04-09 16:01:01 +02:00
),
2019-04-19 17:24:56 +02:00
name
2019-04-09 16:01:01 +02:00
);
});
};
break;
}
case 'morphMany': {
const collection = details.plugin
2019-04-09 16:01:01 +02:00
? strapi.plugins[details.plugin].models[
details.collection
]
: strapi.models[details.collection];
const globalId = `${collection.collectionName}_morph`;
loadedModel[name] = function() {
2019-03-13 19:27:18 +01:00
return this.morphMany(
GLOBALS[globalId],
details.via,
2019-04-19 17:24:56 +02:00
`${definition.collectionName}`
2019-03-13 19:27:18 +01:00
).query(qb => {
qb.where(
2019-04-09 16:01:01 +02:00
_.get(
collection,
`attributes.${details.via}.filter`,
2019-04-19 17:24:56 +02:00
'field'
2019-04-09 16:01:01 +02:00
),
2019-04-19 17:24:56 +02:00
name
2019-03-13 19:27:18 +01:00
);
});
};
break;
}
case 'belongsToMorph':
case 'belongsToManyMorph': {
2019-03-13 19:27:18 +01:00
const association = definition.associations.find(
2019-04-19 17:24:56 +02:00
association => association.alias === name
2019-03-13 19:27:18 +01:00
);
const morphValues = association.related.map(id => {
2019-03-13 19:27:18 +01:00
let models = Object.values(strapi.models).filter(
2019-04-19 17:24:56 +02:00
model => model.globalId === id
2019-03-13 19:27:18 +01:00
);
if (models.length === 0) {
2019-04-09 16:01:01 +02:00
models = Object.keys(strapi.plugins).reduce(
(acc, current) => {
const models = Object.values(
2019-04-19 17:24:56 +02:00
strapi.plugins[current].models
2019-04-09 16:01:01 +02:00
).filter(model => model.globalId === id);
if (acc.length === 0 && models.length > 0) {
acc = models;
}
2019-04-09 16:01:01 +02:00
return acc;
},
2019-04-19 17:24:56 +02:00
[]
2019-04-09 16:01:01 +02:00
);
}
if (models.length === 0) {
2019-03-13 19:27:18 +01:00
strapi.log.error(
2019-04-19 17:24:56 +02:00
`Impossible to register the '${model}' model.`
2019-04-09 16:01:01 +02:00
);
strapi.log.error(
2019-04-19 17:24:56 +02:00
'The collection name cannot be found for the morphTo method.'
2019-03-13 19:27:18 +01:00
);
strapi.stop();
}
return models[0].collectionName;
});
// Define new model.
const options = {
tableName: `${definition.collectionName}_morph`,
[definition.collectionName]: function() {
2019-03-13 19:27:18 +01:00
return this.belongsTo(
GLOBALS[definition.globalId],
2019-04-19 17:24:56 +02:00
`${definition.collectionName}_id`
);
},
related: function() {
return this.morphTo(
name,
2019-03-13 19:27:18 +01:00
...association.related.map((id, index) => [
GLOBALS[id],
morphValues[index],
2019-04-19 17:24:56 +02:00
])
);
},
};
GLOBALS[options.tableName] = ORM.Model.extend(options);
// Set polymorphic table name to the main model.
target[model].morph = GLOBALS[options.tableName];
// 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') {
2019-03-13 19:27:18 +01:00
return this.hasOne(
GLOBALS[options.tableName],
2019-04-19 17:24:56 +02:00
`${definition.collectionName}_id`
2019-03-13 19:27:18 +01:00
);
}
2019-03-13 19:27:18 +01:00
return this.hasMany(
GLOBALS[options.tableName],
2019-04-19 17:24:56 +02:00
`${definition.collectionName}_id`
);
};
break;
}
default: {
break;
}
2017-11-15 16:59:12 +01:00
}
done();
});
if (_.isEmpty(definition.attributes)) {
done();
}
2017-11-15 16:59:12 +01:00
});
};
2017-11-28 15:00:49 +01:00
// Mount `./api` models.
2019-04-09 16:01:01 +02:00
mountModels(
_.pickBy(strapi.models, { connection: connectionName }),
2019-04-19 17:24:56 +02:00
strapi.models
2019-04-09 16:01:01 +02:00
);
// Mount `./admin` models.
2019-04-09 16:01:01 +02:00
mountModels(
_.pickBy(strapi.admin.models, { connection: connectionName }),
2019-04-19 17:24:56 +02:00
strapi.admin.models
2019-04-09 16:01:01 +02:00
);
// Mount `./plugins` models.
_.forEach(strapi.plugins, (plugin, name) => {
mountModels(
_.pickBy(strapi.plugins[name].models, {
connection: connectionName,
}),
plugin.models,
2019-04-19 17:24:56 +02:00
name
);
});
2017-11-15 17:27:07 +01:00
});
2018-01-24 20:15:11 +05:30
2019-04-19 17:24:56 +02:00
return Promise.all(databaseUpdates).then(() => cb(), cb);
},
getQueryParams: (value, type, key) => {
const result = {};
switch (type) {
case '=':
result.key = `where.${key}`;
result.value = {
symbol: '=',
value,
};
break;
case '_ne':
result.key = `where.${key}`;
result.value = {
symbol: '!=',
value,
};
break;
case '_lt':
result.key = `where.${key}`;
result.value = {
symbol: '<',
value,
};
break;
case '_gt':
result.key = `where.${key}`;
result.value = {
symbol: '>',
value,
};
break;
case '_lte':
result.key = `where.${key}`;
result.value = {
symbol: '<=',
value,
};
break;
case '_gte':
result.key = `where.${key}`;
result.value = {
symbol: '>=',
value,
};
break;
case '_sort':
result.key = 'sort';
result.value = {
key,
order: value.toUpperCase(),
};
break;
case '_start':
result.key = 'start';
result.value = parseFloat(value);
break;
case '_limit':
result.key = 'limit';
result.value = parseFloat(value);
break;
case '_populate':
result.key = 'populate';
result.value = value;
break;
case '_contains':
case '_containss':
result.key = `where.${key}`;
result.value = {
symbol: 'like',
value: `%${value}%`,
};
break;
case '_in':
result.key = `where.${key}`;
result.value = {
symbol: 'IN',
value: _.castArray(value),
};
break;
case '_nin':
result.key = `where.${key}`;
result.value = {
symbol: 'NOT IN',
value: _.castArray(value),
};
break;
default:
return undefined;
}
return result;
},
2019-03-13 19:27:18 +01:00
buildQuery,
2017-09-13 12:18:54 +02:00
},
2019-04-19 17:24:56 +02:00
relations
);
2016-03-18 11:12:50 +01:00
return hook;
};