580 lines
23 KiB
JavaScript
Raw Normal View History

2016-07-12 11:15:01 +02:00
'use strict';
/**
* Module dependencies
*/
// Public node modules.
const url = require('url');
const path = require('path');
2016-07-12 11:15:01 +02:00
const _ = require('lodash');
const mongoose = require('mongoose');
const Mongoose = mongoose.Mongoose;
const mongooseUtils = require('mongoose/lib/utils');
2016-07-12 11:15:01 +02:00
2018-05-04 18:09:55 +02:00
// Strapi helpers for models.
2018-08-29 23:27:49 +09:00
const { models: utilsModels } = require('strapi-utils');
2018-05-04 18:09:55 +02:00
2016-07-14 11:06:58 +02:00
// Local helpers.
const utils = require('./utils/');
const relations = require('./relations');
2016-07-14 11:06:58 +02:00
2016-07-12 11:15:01 +02:00
/**
2017-11-17 14:23:26 +01:00
* Mongoose hook
2016-07-12 11:15:01 +02:00
*/
2018-05-04 18:09:55 +02:00
/* eslint-disable prefer-template */
/* eslint-disable no-case-declarations */
/* eslint-disable no-const-assign */
/* eslint-disable no-unused-vars */
2018-08-29 23:27:49 +09:00
module.exports = function (strapi) {
const hook = _.merge({
/**
* Default options
*/
defaults: {
defaultConnection: 'default',
host: 'localhost',
port: 27017,
database: 'strapi',
authenticationDatabase: '',
ssl: false,
debug: false
},
2018-02-07 00:19:05 +01:00
2018-08-29 23:27:49 +09:00
/**
* Initialize the hook
*/
2018-09-12 14:12:09 +09:00
initialize: cb =>
_.forEach(_.pickBy(strapi.config.connections, {connector: 'strapi-hook-mongoose'}), async (connection, connectionName) => {
2018-08-29 23:27:49 +09:00
const instance = new Mongoose();
2018-08-29 23:50:19 +09:00
const { uri, host, port, username, password, database, srv } = _.defaults(connection.settings, strapi.config.hook.settings.mongoose);
2018-08-29 23:27:49 +09:00
const uriOptions = uri ? url.parse(uri, true).query : {};
const { authenticationDatabase, ssl, debug } = _.defaults(connection.options, uriOptions, strapi.config.hook.settings.mongoose);
2018-08-31 00:47:45 +09:00
const isSrv = srv === true || srv === 'true';
2018-02-12 18:54:34 +01:00
2018-08-29 23:27:49 +09:00
// Connect to mongo database
const connectOptions = {};
2019-01-23 16:56:04 +01:00
const options = {
useFindAndModify: false
};
2018-08-29 23:27:49 +09:00
if (!_.isEmpty(username)) {
connectOptions.user = username;
2018-02-12 18:54:34 +01:00
2018-08-29 23:27:49 +09:00
if (!_.isEmpty(password)) {
connectOptions.pass = password;
}
}
2018-08-26 03:26:57 +09:00
2018-08-29 23:27:49 +09:00
if (!_.isEmpty(authenticationDatabase)) {
connectOptions.authSource = authenticationDatabase;
}
2018-08-26 03:26:57 +09:00
2018-08-29 23:27:49 +09:00
connectOptions.ssl = ssl === true || ssl === 'true';
connectOptions.useNewUrlParser = true;
2018-08-29 23:50:19 +09:00
connectOptions.dbName = database;
2019-01-23 16:56:04 +01:00
connectOptions.useCreateIndex = true;
2018-08-26 03:26:57 +09:00
2018-08-29 23:27:49 +09:00
options.debug = debug === true || debug === 'true';
2018-08-26 03:26:57 +09:00
2018-09-12 14:12:09 +09:00
try {
/* FIXME: for now, mongoose doesn't support srv auth except the way including user/pass in URI.
* https://github.com/Automattic/mongoose/issues/6881 */
2018-10-08 16:45:24 +02:00
await instance.connect(uri || `mongodb${isSrv ? '+srv' : ''}://${username}:${password}@${host}${ !isSrv ? ':' + port : '' }/`, connectOptions);
2018-09-12 14:12:09 +09:00
} catch ({message}) {
2018-10-08 16:45:24 +02:00
const errMsg = message.includes(`:${port}`) ? 'Make sure your MongoDB database is running...' : message;
2018-09-12 14:12:09 +09:00
return cb(errMsg);
2018-08-29 23:27:49 +09:00
}
2017-07-24 19:58:03 +02:00
try {
// Require `config/functions/mongoose.js` file to customize connection.
require(path.resolve(
strapi.config.appPath,
'config',
'functions',
'mongoose.js'
))(instance, connection);
} catch (err) {
// This is not an error if the file is not found.
}
2018-09-12 14:12:09 +09:00
Object.keys(options, key => instance.set(key, options[key]));
2018-10-08 16:45:24 +02:00
const mountModels = (models, target, plugin = false) => {
if (!target) return;
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
const loadedAttributes = _.after(_.size(models), () => {
_.forEach(models, (definition, model) => {
try {
let collection = strapi.config.hook.settings.mongoose.collections[mongooseUtils.toCollectionName(definition.globalName)];
// Set the default values to model settings.
_.defaults(definition, {
primaryKey: '_id'
});
// Initialize lifecycle callbacks.
const preLifecycle = {
validate: 'beforeCreate',
findOneAndUpdate: 'beforeUpdate',
findOneAndRemove: 'beforeDestroy',
remove: 'beforeDestroy',
update: 'beforeUpdate',
find: 'beforeFetchAll',
findOne: 'beforeFetch',
save: 'beforeSave'
};
/*
Override populate path for polymorphic association.
It allows us to make Upload.find().populate('related')
instead of Upload.find().populate('related.item')
*/
const morphAssociations = definition.associations.filter(association => association.nature.toLowerCase().indexOf('morph') !== -1);
if (morphAssociations.length > 0) {
morphAssociations.forEach(association => {
Object.keys(preLifecycle)
.filter(key => key.indexOf('find') !== -1)
.forEach(key => {
collection.schema.pre(key, function (next) {
if (this._mongooseOptions.populate && this._mongooseOptions.populate[association.alias]) {
if (association.nature === 'oneToManyMorph' || association.nature === 'manyToManyMorph') {
this._mongooseOptions.populate[association.alias].match = {
[`${association.via}.${association.filter}`]: association.alias,
[`${association.via}.kind`]: definition.globalId
};
// Select last related to an entity.
this._mongooseOptions.populate[association.alias].options = {
sort: '-createdAt'
};
} else {
this._mongooseOptions.populate[association.alias].path = `${association.alias}.ref`;
2018-08-29 23:27:49 +09:00
}
2019-01-25 17:24:21 +01:00
} else {
if (!this._mongooseOptions.populate) {
this._mongooseOptions.populate = {};
}
// Images are not displayed in populated data.
2019-01-28 11:56:27 +01:00
// We automatically populate morph relations.
2019-01-25 17:24:21 +01:00
if (association.nature === 'oneToManyMorph' || association.nature === 'manyToManyMorph') {
this._mongooseOptions.populate[association.alias] = {
path: association.alias,
match: {
[`${association.via}.${association.filter}`]: association.alias,
[`${association.via}.kind`]: definition.globalId
},
options: {
sort: '-createdAt'
},
select: undefined,
model: undefined,
_docs: {}
};
}
2018-10-08 16:45:24 +02:00
}
next();
2018-08-29 23:27:49 +09:00
});
});
});
2018-10-08 16:45:24 +02:00
}
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
_.forEach(preLifecycle, (fn, key) => {
if (_.isFunction(target[model.toLowerCase()][fn])) {
collection.schema.pre(key, function (next) {
target[model.toLowerCase()][fn](this).then(next).catch(err => strapi.log.error(err));
2018-08-29 23:27:49 +09:00
});
2018-10-08 16:45:24 +02:00
}
});
const postLifecycle = {
validate: 'afterCreate',
findOneAndRemove: 'afterDestroy',
remove: 'afterDestroy',
update: 'afterUpdate',
find: 'afterFetchAll',
findOne: 'afterFetch',
save: 'afterSave'
};
// Mongoose doesn't allow post 'remove' event on model.
// See https://github.com/Automattic/mongoose/issues/3054
_.forEach(postLifecycle, (fn, key) => {
if (_.isFunction(target[model.toLowerCase()][fn])) {
collection.schema.post(key, function (doc, next) {
target[model.toLowerCase()][fn](this, doc).then(next).catch(err => {
strapi.log.error(err);
next(err);
});
2018-10-08 16:45:24 +02:00
});
}
});
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
// Add virtual key to provide populate and reverse populate
_.forEach(_.pickBy(definition.loadedModel, model => {
return model.type === 'virtual';
}), (value, key) => {
collection.schema.virtual(key.replace('_v', ''), {
ref: value.ref,
localField: '_id',
foreignField: value.via,
justOne: value.justOne || false
});
});
// Use provided timestamps if the elemnets in the array are string else use default.
if (_.isArray(_.get(definition, 'options.timestamps'))) {
const timestamps = {
createdAt: _.isString(_.get(definition, 'options.timestamps[0]')) ? _.get(definition, 'options.timestamps[0]') : 'createdAt',
updatedAt: _.isString(_.get(definition, 'options.timestamps[1]')) ? _.get(definition, 'options.timestamps[1]') : 'updatedAt'
};
collection.schema.set('timestamps', timestamps);
} else {
collection.schema.set('timestamps', _.get(definition, 'options.timestamps') === true);
2019-01-23 15:19:34 +01:00
_.set(definition, 'options.timestamps', _.get(definition, 'options.timestamps') === true ? ['createdAt', 'updatedAt'] : false);
}
2018-10-08 16:45:24 +02:00
collection.schema.set('minimize', _.get(definition, 'options.minimize', false) === true);
collection.schema.options.toObject = collection.schema.options.toJSON = {
virtuals: true,
transform: function (doc, returned, opts) {
// Remover $numberDecimal nested property.
Object.keys(returned)
.filter(key => returned[key] instanceof mongoose.Types.Decimal128)
.forEach((key, index) => {
// Parse to float number.
returned[key] = parseFloat(returned[key].toString());
2018-08-29 23:27:49 +09:00
});
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
morphAssociations.forEach(association => {
if (Array.isArray(returned[association.alias]) && returned[association.alias].length > 0) {
// Reformat data by bypassing the many-to-many relationship.
switch (association.nature) {
case 'oneMorphToOne':
returned[association.alias] = returned[association.alias][0].ref;
break;
case 'manyMorphToMany':
case 'manyMorphToOne':
returned[association.alias] = returned[association.alias].map(obj => obj.ref);
break;
default:
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
}
}
});
2018-08-29 01:33:58 +09:00
}
2018-10-08 16:45:24 +02:00
};
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
// Instantiate model.
const Model = instance.model(definition.globalId, collection.schema, definition.collectionName);
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
if (!plugin) {
global[definition.globalName] = Model;
2018-08-29 01:33:58 +09:00
}
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
// Expose ORM functions through the `target` object.
target[model] = _.assign(Model, target[model]);
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
// Push attributes to be aware of model schema.
target[model]._attributes = definition.attributes;
target[model].updateRelations = relations.update;
} catch (err) {
strapi.log.error('Impossible to register the `' + model + '` model.');
strapi.log.error(err);
2018-08-29 23:27:49 +09:00
strapi.stop();
}
2018-10-08 16:45:24 +02:00
});
});
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
// Parse every authenticated model.
_.forEach(models, (definition, model) => {
definition.globalName = _.upperFirst(_.camelCase(definition.globalId));
// Make sure the model has a connection.
// If not, use the default connection.
if (_.isEmpty(definition.connection)) {
definition.connection = strapi.config.currentEnvironment.database.defaultConnection;
}
// Make sure this connection exists.
if (!_.has(strapi.config.connections, definition.connection)) {
strapi.log.error('The connection `' + definition.connection + '` specified in the `' + model + '` model does not exist.');
strapi.stop();
}
// Add some informations about ORM & client connection
definition.orm = 'mongoose';
definition.client = _.get(strapi.config.connections[definition.connection], 'client');
definition.associations = [];
// Register the final model for Mongoose.
definition.loadedModel = _.cloneDeep(definition.attributes);
// Initialize the global variable with the
// capitalized model name.
if (!plugin) {
global[definition.globalName] = {};
}
if (_.isEmpty(definition.attributes)) {
// Generate empty schema
_.set(strapi.config.hook.settings.mongoose, 'collections.' + mongooseUtils.toCollectionName(definition.globalName) + '.schema', new instance.Schema({}));
return loadedAttributes();
}
// Call this callback function after we are done parsing
// all attributes for relationships-- see below.
const done = _.after(_.size(definition.attributes), () => {
// Generate schema without virtual populate
const schema = new instance.Schema(_.omitBy(definition.loadedModel, model => {
return model.type === 'virtual';
}));
_.set(strapi.config.hook.settings.mongoose, 'collections.' + mongooseUtils.toCollectionName(definition.globalName) + '.schema', schema);
loadedAttributes();
});
2018-10-08 16:45:24 +02: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') || '';
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
// Build associations key
utilsModels.defineAssociations(model.toLowerCase(), definition, details, name);
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
if (_.isEmpty(verbose)) {
definition.loadedModel[name].type = utils(instance).convertType(details.type);
2018-08-29 23:27:49 +09:00
}
2018-10-08 16:45:24 +02:00
switch (verbose) {
case 'hasOne': {
const ref = details.plugin ? strapi.plugins[details.plugin].models[details.model].globalId : strapi.models[details.model].globalId;
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
definition.loadedModel[name] = {
type: instance.Schema.Types.ObjectId,
ref
};
break;
2018-08-29 01:33:58 +09:00
}
2018-10-08 16:45:24 +02:00
case 'hasMany': {
const FK = _.find(definition.associations, {alias: name});
const ref = details.plugin ? strapi.plugins[details.plugin].models[details.collection].globalId : strapi.models[details.collection].globalId;
2018-10-08 16:45:24 +02:00
if (FK) {
2018-08-29 23:27:49 +09:00
definition.loadedModel[name] = {
2018-10-08 16:45:24 +02:00
type: 'virtual',
ref,
via: FK.via,
justOne: false
2018-08-29 23:27:49 +09:00
};
2018-08-29 01:33:58 +09:00
2018-10-08 16:45:24 +02:00
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
} else {
definition.loadedModel[name] = [{
type: instance.Schema.Types.ObjectId,
ref
}];
2018-08-29 23:27:49 +09:00
}
2018-10-08 16:45:24 +02:00
break;
}
case 'belongsTo': {
const FK = _.find(definition.associations, {alias: name});
const ref = details.plugin ? strapi.plugins[details.plugin].models[details.model].globalId : strapi.models[details.model].globalId;
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
if (FK && FK.nature !== 'oneToOne' && FK.nature !== 'manyToOne' && FK.nature !== 'oneWay' && FK.nature !== 'oneToMorph') {
2018-08-29 23:27:49 +09:00
definition.loadedModel[name] = {
type: 'virtual',
ref,
2018-10-08 16:45:24 +02:00
via: FK.via,
2018-08-29 23:27:49 +09:00
justOne: true
};
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
2018-10-08 16:45:24 +02:00
} else {
definition.loadedModel[name] = {
type: instance.Schema.Types.ObjectId,
ref
};
2018-08-29 23:27:49 +09:00
}
2018-10-08 16:45:24 +02:00
break;
}
case 'belongsToMany': {
const FK = _.find(definition.associations, {alias: name});
const ref = details.plugin ? strapi.plugins[details.plugin].models[details.collection].globalId : strapi.models[details.collection].globalId;
// One-side of the relationship has to be a virtual field to be bidirectional.
if ((FK && _.isUndefined(FK.via)) || details.dominant !== true) {
2018-08-29 23:27:49 +09:00
definition.loadedModel[name] = {
type: 'virtual',
ref,
2018-10-08 16:45:24 +02:00
via: FK.via
2018-08-29 23:27:49 +09:00
};
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
2018-10-08 16:45:24 +02:00
} else {
2018-08-29 23:27:49 +09:00
definition.loadedModel[name] = [{
2018-10-08 16:45:24 +02:00
type: instance.Schema.Types.ObjectId,
ref
2018-08-29 23:27:49 +09:00
}];
}
2018-10-08 16:45:24 +02:00
break;
2018-08-29 23:27:49 +09:00
}
2018-10-08 16:45:24 +02:00
case 'morphOne': {
const FK = _.find(definition.associations, {alias: name});
const ref = details.plugin ? strapi.plugins[details.plugin].models[details.model].globalId : strapi.models[details.model].globalId;
definition.loadedModel[name] = {
type: 'virtual',
ref,
via: `${FK.via}.ref`,
justOne: true
};
2018-10-08 16:45:24 +02:00
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
break;
}
case 'morphMany': {
const FK = _.find(definition.associations, {alias: name});
const ref = details.plugin ? strapi.plugins[details.plugin].models[details.collection].globalId : strapi.models[details.collection].globalId;
definition.loadedModel[name] = {
type: 'virtual',
ref,
via: `${FK.via}.ref`
};
2018-10-08 16:45:24 +02:00
// Set this info to be able to see if this field is a real database's field.
details.isVirtual = true;
break;
}
case 'belongsToMorph': {
definition.loadedModel[name] = {
kind: String,
[details.filter]: String,
ref: {
type: instance.Schema.Types.ObjectId,
refPath: `${name}.kind`
}
};
break;
}
case 'belongsToManyMorph': {
definition.loadedModel[name] = [{
kind: String,
[details.filter]: String,
ref: {
type: instance.Schema.Types.ObjectId,
refPath: `${name}.kind`
}
}];
break;
}
default:
break;
}
2018-08-29 23:27:49 +09:00
2018-10-08 16:45:24 +02:00
done();
});
2018-08-29 23:27:49 +09:00
});
2018-10-08 16:45:24 +02:00
};
// Mount `./api` models.
mountModels(_.pickBy(strapi.models, { connection: connectionName }), strapi.models);
// Mount `./plugins` models.
_.forEach(strapi.plugins, (plugin, name) => {
mountModels(_.pickBy(strapi.plugins[name].models, { connection: connectionName }), plugin.models, name);
});
2018-08-26 03:26:57 +09:00
2018-10-08 16:45:24 +02:00
cb();
2018-09-12 14:12:09 +09:00
}),
2018-08-29 23:27:49 +09:00
getQueryParams: (value, type, key) => {
const result = {};
switch (type) {
case '=':
result.key = `where.${key}`;
result.value = value;
break;
case '_ne':
result.key = `where.${key}.$ne`;
result.value = value;
break;
case '_lt':
result.key = `where.${key}.$lt`;
result.value = value;
break;
case '_gt':
result.key = `where.${key}.$gt`;
result.value = value;
break;
case '_lte':
result.key = `where.${key}.$lte`;
result.value = value;
break;
case '_gte':
result.key = `where.${key}.$gte`;
result.value = value;
break;
case '_sort':
result.key = 'sort';
2018-08-29 23:27:49 +09:00
result.value = (_.toLower(value) === 'desc') ? '-' : '';
result.value += key;
break;
case '_start':
result.key = 'start';
2018-08-29 23:27:49 +09:00
result.value = parseFloat(value);
break;
case '_limit':
result.key = 'limit';
2018-08-29 23:27:49 +09:00
result.value = parseFloat(value);
break;
case '_populate':
result.key = `populate`;
result.value = value;
break;
2018-08-29 23:27:49 +09:00
case '_contains':
result.key = `where.${key}`;
result.value = {
$regex: value,
$options: 'i',
};
break;
case '_containss':
result.key = `where.${key}.$regex`;
result.value = value;
break;
case '_in':
result.key = `where.${key}.$in`;
result.value = value;
break;
default:
result = undefined;
}
return result;
}
}, relations);
2016-07-12 11:15:01 +02:00
return hook;
2019-01-28 11:56:27 +01:00
};