91 lines
2.3 KiB
Plaintext
Raw Normal View History

2016-03-18 11:12:50 +01:00
'use strict';
2016-03-25 22:22:34 +01:00
/**
* <%= filename %> service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
2016-03-25 22:22:34 +01:00
*/
// Public dependencies.
2016-03-18 11:12:50 +01:00
const _ = require('lodash');
2016-03-25 22:22:34 +01:00
// Strapi utilities.
const utils = require('strapi-bookshelf/lib/utils/');
2016-03-18 11:12:50 +01:00
module.exports = {
/**
* Promise to fetch all <%= idPluralized %>.
2016-03-18 11:12:50 +01:00
*
* @return {Promise}
*/
fetchAll: (params) => {
2017-10-11 17:30:08 +02:00
const convertedParams = strapi.utils.models.convertParams('<%= globalID.toLowerCase() %>', params);
2017-09-13 12:18:54 +02:00
return <%= globalID %>.query(function(qb) {
2017-10-11 17:30:08 +02:00
_.forEach(convertedParams.where, (where, key) => {
2017-09-13 12:18:54 +02:00
qb.where(key, where.symbol, where.value);
});
if (convertedParams.sort) {
qb.orderBy(convertedParams.sort);
}
2017-09-13 12:18:54 +02:00
2017-10-11 17:30:08 +02:00
qb.offset(convertedParams.start);
2017-10-10 15:14:20 +02:00
2017-10-11 17:30:08 +02:00
qb.limit(convertedParams.limit);
2017-09-13 12:18:54 +02:00
}).fetchAll({
withRelated: _.keys(_.groupBy(_.reject(strapi.models.<%= id %>.associations, {autoPopulate: false}), 'alias'))
2016-03-18 11:12:50 +01:00
});
},
/**
* Promise to fetch a/an <%= id %>.
2016-03-18 11:12:50 +01:00
*
* @return {Promise}
*/
fetch: (params) => {
return <%= globalID %>.forge(_.pick(params, 'id')).fetch({
withRelated: _.keys(_.groupBy(_.reject(strapi.models.<%= id %>.associations, {autoPopulate: false}), 'alias'))
2016-03-18 11:12:50 +01:00
});
},
/**
* Promise to add a/an <%= id %>.
2016-03-18 11:12:50 +01:00
*
* @return {Promise}
*/
add: async (values) => {
const data = await <%= globalID %>.forge(_.omit(values, _.keys(_.groupBy(strapi.models.<%= id %>.associations, 'alias')))).save();
2017-11-01 15:16:28 +01:00
await strapi.hook.bookshelf.manageRelations('<%= id %>', _.merge(_.clone(data.toJSON()), { values }));
return data;
2016-03-18 11:12:50 +01:00
},
/**
* Promise to edit a/an <%= id %>.
2016-03-18 11:12:50 +01:00
*
* @return {Promise}
*/
edit: async (params, values) => {
2017-11-01 15:16:28 +01:00
await strapi.hook.bookshelf.manageRelations('<%= id %>', _.merge(_.clone(params), { values }));
return <%= globalID %>.forge(params).save(_.omit(values, _.keys(_.groupBy(strapi.models.<%= id %>.associations, 'alias'))), {path: true});
2016-03-18 11:12:50 +01:00
},
/**
* Promise to remove a/an <%= id %>.
2016-03-18 11:12:50 +01:00
*
* @return {Promise}
*/
remove: (params) => {
_.forEach(<%= globalID %>.associations, async association => {
await <%= globalID %>.forge(params)[association.alias]().detach();
});
return <%= globalID %>.forge(params).destroy();
2016-03-18 11:12:50 +01:00
}
};