343 lines
9.1 KiB
Plaintext
Raw Normal View History

'use strict';
/* global <%= globalID %> */
/**
2017-01-11 18:24:26 +01:00
* <%= filename %> service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
*/
// Public dependencies.
const _ = require('lodash');
const buildTempFieldPath = field => {
return `__${field}`;
};
const restoreRealFieldPath = (field, prefix) => {
return `${prefix}${field}`;
};
export const generateLookupStage = (
strapiModel,
{ whitelistedPopulate = null, prefixPath = '' } = {}
) => {
const result = strapiModel.associations
.filter(ast => {
if (whitelistedPopulate) {
return _.includes(whitelistedPopulate, ast.alias);
}
return ast.autoPopulate;
})
.reduce((acc, ast) => {
const model = ast.plugin
? strapi.plugins[ast.plugin].models[ast.collection || ast.model]
: strapi.models[ast.collection || ast.model];
const from = model.collectionName;
const isDominantAssociation = ast.dominant || !!ast.model;
const _localField = !isDominantAssociation
? '_id'
: ast.via === strapiModel.collectionName || ast.via === 'related'
? '_id'
: ast.alias;
const localField = `${prefixPath}${_localField}`;
const foreignField = ast.filter
? `${ast.via}.ref`
: isDominantAssociation
? ast.via === strapiModel.collectionName
? ast.via
: '_id'
: ast.via === strapiModel.collectionName
? '_id'
: ast.via;
// Add the juncture like the `.populate()` function
const asTempPath = buildTempFieldPath(ast.alias, prefixPath);
const asRealPath = restoreRealFieldPath(ast.alias, prefixPath);
acc.push({
$lookup: {
from,
localField,
foreignField,
as: asTempPath,
},
});
// Unwind the relation's result if only one is expected
if (ast.type === 'model') {
acc.push({
$unwind: {
path: `$${asTempPath}`,
preserveNullAndEmptyArrays: true,
},
});
}
// Preserve relation field if it is empty
acc.push({
$addFields: {
[asRealPath]: {
$ifNull: [`$${asTempPath}`, null],
},
},
});
// Remove temp field
acc.push({
$project: {
[asTempPath]: 0,
},
});
return acc;
}, []);
return result;
};
export const generateMatchStage = (
strapiModel,
filters,
{ prefixPath = '' } = {}
) => {
const result = _.chain(filters)
.get('relations')
.reduce((acc, relationFilters, relationName) => {
const association = strapiModel.associations.find(
a => a.alias === relationName
);
// Ignore association if it's not been found
if (!association) {
return acc;
}
const model = association.plugin
? strapi.plugins[association.plugin].models[
association.collection || association.model
]
: strapi.models[association.collection || association.model];
_.forEach(relationFilters, (value, key) => {
if (key !== 'relations') {
acc.push({
$match: { [`${prefixPath}${relationName}.${key}`]: value },
});
} else {
const nextPrefixedPath = `${prefixPath}${relationName}.`;
acc.push(
...generateLookupStage(model, {
whitelistedPopulate: _.keys(value),
prefixPath: nextPrefixedPath,
}),
...generateMatchStage(model, relationFilters, {
prefixPath: nextPrefixedPath,
})
);
}
});
return acc;
}, [])
.value();
return result;
};
module.exports = {
/**
* Promise to fetch all <%= humanizeIdPluralized %>.
*
* @return {Promise}
*/
2017-01-11 18:24:26 +01:00
fetchAll: (params) => {
// Convert `params` object to filters compatible with Mongo.
const filters = strapi.utils.models.convertParams('<%= globalID.toLowerCase() %>', params);
// Generate stages.
const populate = generateLookupStage(<%= globalID %>);
const match = generateMatchStage(<%= globalID %>, filters);
const result = <%= globalID %>.aggregate([
{
$match: filters.where, // Direct relation filter
},
...populate, // Nested-Population
...match, // Nested relation filter
])
.skip(filters.start)
.limit(filters.limit);
if (filters.sort) result.sort(filters.sort);
return result;
},
/**
* Promise to fetch a/an <%= id %>.
*
* @return {Promise}
*/
2017-01-11 18:24:26 +01:00
fetch: (params) => {
// Select field to populate.
const populate = <%= globalID %>.associations
.filter(ast => ast.autoPopulate !== false)
.map(ast => ast.alias)
.join(' ');
2017-10-10 15:14:20 +02:00
return <%= globalID %>
2017-12-20 13:45:53 +01:00
.findOne(_.pick(params, _.keys(<%= globalID %>.schema.paths)))
.populate(populate);
},
2018-05-29 15:48:07 +03:00
/**
* Promise to count <%= humanizeIdPluralized %>.
*
* @return {Promise}
*/
count: (params) => {
// Convert `params` object to filters compatible with Mongo.
const filters = strapi.utils.models.convertParams('<%= globalID.toLowerCase() %>', params);
return <%= globalID %>
.count()
.where(filters.where);
},
/**
* Promise to add a/an <%= id %>.
*
* @return {Promise}
*/
add: async (values) => {
// Extract values related to relational data.
const relations = _.pick(values, <%= globalID %>.associations.map(ast => ast.alias));
const data = _.omit(values, <%= globalID %>.associations.map(ast => ast.alias));
// Create entry with no-relational data.
const entry = await <%= globalID %>.create(data);
// Create relational data and return the entry.
2018-07-19 14:46:03 +02:00
return <%= globalID %>.updateRelations({ _id: entry.id, values: relations });
},
/**
* Promise to edit a/an <%= id %>.
*
* @return {Promise}
*/
2017-10-25 16:24:35 +02:00
edit: async (params, values) => {
// Extract values related to relational data.
const relations = _.pick(values, <%= globalID %>.associations.map(a => a.alias));
const data = _.omit(values, <%= globalID %>.associations.map(a => a.alias));
// Update entry with no-relational data.
const entry = await <%= globalID %>.update(params, data, { multi: true });
// Update relational data and return the entry.
return <%= globalID %>.updateRelations(Object.assign(params, { values: relations }));
},
/**
* Promise to remove a/an <%= id %>.
*
* @return {Promise}
*/
remove: async params => {
// Select field to populate.
const populate = <%= globalID %>.associations
.filter(ast => ast.autoPopulate !== false)
.map(ast => ast.alias)
.join(' ');
2017-01-11 18:24:26 +01:00
// Note: To get the full response of Mongo, use the `remove()` method
// or add spent the parameter `{ passRawResult: true }` as second argument.
const data = await <%= globalID %>
.findOneAndRemove(params, {})
.populate(populate);
if (!data) {
return data;
}
await Promise.all(
<%= globalID %>.associations.map(async association => {
if (!association.via || !data._id) {
return true;
}
const search = _.endsWith(association.nature, 'One') || association.nature === 'oneToMany' ? { [association.via]: data._id } : { [association.via]: { $in: [data._id] } };
const update = _.endsWith(association.nature, 'One') || association.nature === 'oneToMany' ? { [association.via]: null } : { $pull: { [association.via]: data._id } };
// Retrieve model.
const model = association.plugin ?
strapi.plugins[association.plugin].models[association.model || association.collection] :
strapi.models[association.model || association.collection];
return model.update(search, update, { multi: true });
})
);
return data;
},
2018-07-05 10:22:43 +02:00
/**
* Promise to search a/an <%= id %>.
*
* @return {Promise}
*/
2018-07-05 11:28:55 +02:00
search: async (params) => {
2018-07-05 10:22:43 +02:00
// Convert `params` object to filters compatible with Mongo.
const filters = strapi.utils.models.convertParams('<%= globalID.toLowerCase() %>', params);
// Select field to populate.
const populate = <%= globalID %>.associations
.filter(ast => ast.autoPopulate !== false)
.map(ast => ast.alias)
.join(' ');
const $or = Object.keys(<%= globalID %>.attributes).reduce((acc, curr) => {
switch (<%= globalID %>.attributes[curr].type) {
case 'integer':
case 'float':
case 'decimal':
if (!_.isNaN(_.toNumber(params._q))) {
return acc.concat({ [curr]: params._q });
}
return acc;
case 'string':
case 'text':
case 'password':
return acc.concat({ [curr]: { $regex: params._q, $options: 'i' } });
case 'boolean':
if (params._q === 'true' || params._q === 'false') {
return acc.concat({ [curr]: params._q === 'true' });
}
return acc;
default:
return acc;
}
}, []);
return <%= globalID %>
.find({ $or })
.sort(filters.sort)
.skip(filters.start)
.limit(filters.limit)
.populate(populate);
}
};