457 lines
12 KiB
JavaScript
Raw Normal View History

2019-07-15 15:33:42 +02:00
'use strict';
/**
* Implementation of model queries for mongo
*/
const _ = require('lodash');
const {
convertRestQueryParams,
buildQuery,
models: modelUtils,
} = require('strapi-utils');
module.exports = ({ model, modelKey, strapi }) => {
const hasPK = obj => _.has(obj, model.primaryKey) || _.has(obj, 'id');
const getPK = obj =>
_.has(obj, model.primaryKey) ? obj[model.primaryKey] : obj.id;
const assocKeys = model.associations.map(ast => ast.alias);
2019-10-22 18:01:03 +02:00
const componentKeys = Object.keys(model.attributes).filter(key => {
return model.attributes[key].type === 'component';
2019-07-15 15:33:42 +02:00
});
2019-10-22 18:01:03 +02:00
const excludedKeys = assocKeys.concat(componentKeys);
2019-07-15 15:33:42 +02:00
const defaultPopulate = model.associations
.filter(ast => ast.autoPopulate !== false)
.map(ast => ast.alias);
const pickRelations = values => {
return _.pick(values, assocKeys);
};
const omitExernalValues = values => {
return _.omit(values, excludedKeys);
};
2019-10-22 18:01:03 +02:00
async function createComponents(entry, values) {
if (componentKeys.length === 0) return;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
for (let key of componentKeys) {
2019-07-15 15:33:42 +02:00
const attr = model.attributes[key];
2019-10-22 18:01:03 +02:00
const { component, required = false, repeatable = false } = attr;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const componentModel = strapi.components[component];
2019-07-15 15:33:42 +02:00
if (required === true && !_.has(values, key)) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} is required`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
if (!_.has(values, key)) continue;
2019-10-22 18:01:03 +02:00
const componentValue = values[key];
2019-07-15 15:33:42 +02:00
if (repeatable === true) {
2019-10-22 18:01:03 +02:00
validateRepeatableInput(componentValue, { key, ...attr });
const components = await Promise.all(
componentValue.map(value => {
return strapi.query(component).create(value);
})
2019-07-15 15:33:42 +02:00
);
2019-10-22 18:01:03 +02:00
const componentsArr = components.map(componentEntry => ({
kind: componentModel.globalId,
ref: componentEntry,
2019-07-15 15:33:42 +02:00
}));
2019-10-22 18:01:03 +02:00
entry[key] = componentsArr;
2019-07-15 15:33:42 +02:00
await entry.save();
} else {
2019-10-22 18:01:03 +02:00
validateNonRepeatableInput(componentValue, { key, ...attr });
if (componentValue === null) continue;
2019-10-22 18:01:03 +02:00
const componentEntry = await strapi
.query(component)
.create(componentValue);
2019-07-15 15:33:42 +02:00
entry[key] = [
{
2019-10-22 18:01:03 +02:00
kind: componentModel.globalId,
ref: componentEntry,
2019-07-15 15:33:42 +02:00
},
];
await entry.save();
}
}
}
2019-10-22 18:01:03 +02:00
async function updateComponents(entry, values) {
if (componentKeys.length === 0) return;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
for (let key of componentKeys) {
// if key isn't present then don't change the current component data
2019-07-15 15:33:42 +02:00
if (!_.has(values, key)) continue;
const attr = model.attributes[key];
2019-10-22 18:01:03 +02:00
const { component, repeatable = false } = attr;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const componentModel = strapi.components[component];
const componentValue = values[key];
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const updateOrCreateComponent = async value => {
2019-07-15 15:33:42 +02:00
// check if value has an id then update else create
if (hasPK(value)) {
2019-10-22 18:01:03 +02:00
return strapi.query(component).update(
2019-07-15 15:33:42 +02:00
{
[model.primaryKey]: getPK(value),
},
value
2019-07-15 15:33:42 +02:00
);
}
2019-10-22 18:01:03 +02:00
return strapi.query(component).create(value);
2019-07-15 15:33:42 +02:00
};
if (repeatable === true) {
2019-10-22 18:01:03 +02:00
validateRepeatableInput(componentValue, { key, ...attr });
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
await deleteOldComponents(entry, componentValue, {
key,
componentModel,
});
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const components = await Promise.all(
componentValue.map(updateOrCreateComponent)
);
const componentsArr = components.map(component => ({
kind: componentModel.globalId,
ref: component,
2019-07-15 15:33:42 +02:00
}));
2019-10-22 18:01:03 +02:00
entry[key] = componentsArr;
2019-07-15 15:33:42 +02:00
await entry.save();
} else {
2019-10-22 18:01:03 +02:00
validateNonRepeatableInput(componentValue, { key, ...attr });
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
await deleteOldComponents(entry, componentValue, {
key,
componentModel,
});
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
if (componentValue === null) continue;
2019-10-22 18:01:03 +02:00
const component = await updateOrCreateComponent(componentValue);
2019-07-15 15:33:42 +02:00
entry[key] = [
{
2019-10-22 18:01:03 +02:00
kind: componentModel.globalId,
ref: component,
2019-07-15 15:33:42 +02:00
},
];
await entry.save();
}
}
return;
}
2019-10-22 18:01:03 +02:00
async function deleteOldComponents(
entry,
componentValue,
{ key, componentModel }
) {
const componentArr = Array.isArray(componentValue)
? componentValue
: [componentValue];
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
const idsToKeep = componentArr.filter(hasPK).map(getPK);
2019-07-15 15:33:42 +02:00
const allIds = await (entry[key] || [])
.filter(el => el.ref)
.map(el => el.ref._id);
// verify the provided ids are realted to this entity.
idsToKeep.forEach(id => {
if (allIds.findIndex(currentId => currentId.toString() === id) === -1) {
const err = new Error(
2019-10-22 18:01:03 +02:00
`Some of the provided components in ${key} are not related to the entity`
2019-07-15 15:33:42 +02:00
);
err.status = 400;
throw err;
}
});
const idsToDelete = allIds.reduce((acc, id) => {
if (idsToKeep.includes(id.toString())) return acc;
return acc.concat(id);
}, []);
if (idsToDelete.length > 0) {
await strapi
2019-10-22 18:01:03 +02:00
.query(componentModel.uid)
.delete({ [`${model.primaryKey}_in`]: idsToDelete });
2019-07-15 15:33:42 +02:00
}
}
2019-10-22 18:01:03 +02:00
async function deleteComponents(entry) {
if (componentKeys.length === 0) return;
2019-07-15 15:33:42 +02:00
2019-10-22 18:01:03 +02:00
for (let key of componentKeys) {
2019-07-15 15:33:42 +02:00
const attr = model.attributes[key];
2019-10-22 18:01:03 +02:00
const { component } = attr;
const componentModel = strapi.components[component];
2019-07-15 15:33:42 +02:00
if (Array.isArray(entry[key]) && entry[key].length > 0) {
const idsToDelete = entry[key].map(el => el.ref);
await strapi
2019-10-22 18:01:03 +02:00
.query(componentModel.uid)
.delete({ [`${model.primaryKey}_in`]: idsToDelete });
2019-07-15 15:33:42 +02:00
}
}
}
2019-07-16 21:24:09 +02:00
function find(params, populate) {
const populateOpt = populate || defaultPopulate;
2019-07-15 15:33:42 +02:00
2019-07-16 21:24:09 +02:00
const filters = convertRestQueryParams(params);
2019-07-15 15:33:42 +02:00
2019-07-16 21:24:09 +02:00
return buildQuery({
model,
filters,
populate: populateOpt,
}).then(results =>
results.map(result => (result ? result.toObject() : null))
);
2019-07-16 21:24:09 +02:00
}
2019-07-15 15:33:42 +02:00
2019-07-18 15:49:24 +02:00
async function findOne(params, populate) {
2019-07-16 21:24:09 +02:00
const primaryKey = getPK(params);
2019-07-15 15:33:42 +02:00
2019-07-16 21:24:09 +02:00
if (primaryKey) {
params = {
[model.primaryKey]: primaryKey,
};
}
2019-07-18 15:49:24 +02:00
const entry = await model
.findOne(params)
.populate(populate || defaultPopulate);
return entry ? entry.toObject() : null;
2019-07-16 21:24:09 +02:00
}
function count(params) {
const filters = convertRestQueryParams(params);
return buildQuery({
model,
filters: { where: filters.where },
}).count();
}
async function create(values) {
// Extract values related to relational data.
const relations = pickRelations(values);
const data = omitExernalValues(values);
// Create entry with no-relational data.
const entry = await model.create(data);
2019-10-22 18:01:03 +02:00
await createComponents(entry, values);
2019-07-16 21:24:09 +02:00
// Create relational data and return the entry.
return model.updateRelations({
[model.primaryKey]: getPK(entry),
values: relations,
});
}
async function update(params, values) {
const primaryKey = getPK(params);
if (primaryKey) {
params = {
[model.primaryKey]: primaryKey,
};
}
2019-07-15 15:33:42 +02:00
2019-07-16 21:24:09 +02:00
const entry = await model.findOne(params);
if (!entry) {
const err = new Error('entry.notFound');
err.status = 404;
throw err;
}
// Extract values related to relational data.
const relations = pickRelations(values);
const data = omitExernalValues(values);
2019-10-22 18:01:03 +02:00
// update components first in case it fails don't update the entity
await updateComponents(entry, values);
2019-07-16 21:24:09 +02:00
// Update entry with no-relational data.
await entry.updateOne(data);
// Update relational data and return the entry.
return model.updateRelations(Object.assign(params, { values: relations }));
}
2019-07-16 23:13:05 +02:00
async function deleteMany(params) {
const primaryKey = getPK(params);
if (primaryKey) return deleteOne(params);
const entries = await find(params);
return await Promise.all(entries.map(entry => deleteOne({ id: entry.id })));
}
2019-07-16 21:24:09 +02:00
async function deleteOne(params) {
const entry = await model
.findOneAndRemove({ [model.primaryKey]: getPK(params) })
.populate(defaultPopulate);
if (!entry) {
const err = new Error('entry.notFound');
err.status = 404;
throw err;
}
2019-10-22 18:01:03 +02:00
await deleteComponents(entry);
2019-07-16 21:24:09 +02:00
await Promise.all(
model.associations.map(async association => {
2019-07-16 23:27:34 +02:00
if (!association.via || !entry._id || association.dominant) {
2019-07-16 21:24:09 +02:00
return true;
}
const search =
_.endsWith(association.nature, 'One') ||
association.nature === 'oneToMany'
2019-07-16 23:27:34 +02:00
? { [association.via]: entry._id }
: { [association.via]: { $in: [entry._id] } };
2019-07-16 21:24:09 +02:00
const update =
_.endsWith(association.nature, 'One') ||
association.nature === 'oneToMany'
? { [association.via]: null }
2019-07-16 23:27:34 +02:00
: { $pull: { [association.via]: entry._id } };
2019-07-16 21:24:09 +02:00
// Retrieve model.
2019-07-16 23:27:34 +02:00
const model = association.plugin
2019-07-16 21:24:09 +02:00
? strapi.plugins[association.plugin].models[
association.model || association.collection
]
: strapi.models[association.model || association.collection];
2019-07-17 00:03:38 +02:00
return model.updateMany(search, update);
2019-07-16 21:24:09 +02:00
})
);
2019-08-23 11:22:45 +02:00
return entry.toObject ? entry.toObject() : null;
2019-07-16 21:24:09 +02:00
}
function search(params, populate) {
// Convert `params` object to filters compatible with Mongo.
const filters = modelUtils.convertParams(modelKey, params);
const $or = buildSearchOr(model, params._q);
return model
.find({ $or })
.sort(filters.sort)
.skip(filters.start)
.limit(filters.limit)
.populate(populate || defaultPopulate)
.then(results =>
results.map(result => (result ? result.toObject() : null))
);
2019-07-16 21:24:09 +02:00
}
function countSearch(params) {
const $or = buildSearchOr(model, params._q);
return model.find({ $or }).countDocuments();
}
return {
findOne,
find,
create,
update,
delete: deleteMany,
count,
search,
countSearch,
2019-07-15 15:33:42 +02:00
};
};
const buildSearchOr = (model, query) => {
return Object.keys(model.attributes).reduce((acc, curr) => {
switch (model.attributes[curr].type) {
case 'integer':
case 'float':
case 'decimal':
if (!_.isNaN(_.toNumber(query))) {
return acc.concat({ [curr]: query });
}
return acc;
case 'string':
case 'text':
case 'password':
return acc.concat({ [curr]: { $regex: query, $options: 'i' } });
case 'boolean':
if (query === 'true' || query === 'false') {
return acc.concat({ [curr]: query === 'true' });
}
return acc;
default:
return acc;
}
}, []);
};
function validateRepeatableInput(value, { key, min, max, required }) {
2019-07-15 15:33:42 +02:00
if (!Array.isArray(value)) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} is repetable. Expected an array`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
value.forEach(val => {
if (typeof val !== 'object' || Array.isArray(val) || val === null) {
const err = new Error(
`Component ${key} has invalid items. Expected each items to be objects`
);
err.status = 400;
throw err;
}
});
if (
(required === true || (required !== true && value.length > 0)) &&
(min && value.length < min)
) {
2019-10-22 18:01:03 +02:00
const err = new Error(
`Component ${key} must contain at least ${min} items`
);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
2019-07-15 15:33:42 +02:00
if (max && value.length > max) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} must contain at most ${max} items`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
}
function validateNonRepeatableInput(value, { key, required }) {
if (typeof value !== 'object' || Array.isArray(value)) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} should be an object`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
if (required === true && value === null) {
2019-10-22 18:01:03 +02:00
const err = new Error(`Component ${key} is required`);
2019-07-15 15:33:42 +02:00
err.status = 400;
throw err;
}
}