'use strict'; /** * <%= filename %> service * * @description: A set of functions similar to controller's actions to avoid code duplication. */ // Public dependencies. const _ = require('lodash'); // Strapi utilities. const utils = require('strapi-bookshelf/lib/utils/'); module.exports = { /** * Promise to fetch all <%= idPluralized %>. * * @return {Promise} */ fetchAll: (params) => { const convertedParams = strapi.utils.models.convertParams('<%= globalID.toLowerCase() %>', params); return <%= globalID %>.query(function(qb) { _.forEach(convertedParams.where, (where, key) => { qb.where(key, where.symbol, where.value); }); if (convertedParams.sort) { qb.orderBy(convertedParams.sort); } qb.offset(convertedParams.start); qb.limit(convertedParams.limit); }).fetchAll({ withRelated: _.keys(_.groupBy(_.reject(strapi.models.<%= id %>.associations, {autoPopulate: false}), 'alias')) }); }, /** * Promise to fetch a/an <%= id %>. * * @return {Promise} */ fetch: (params) => { return <%= globalID %>.forge(_.pick(params, 'id')).fetch({ withRelated: _.keys(_.groupBy(_.reject(strapi.models.<%= id %>.associations, {autoPopulate: false}), 'alias')) }); }, /** * Promise to add a/an <%= id %>. * * @return {Promise} */ add: async (values) => { const data = await <%= globalID %>.forge(_.omit(values, _.keys(_.groupBy(strapi.models.<%= id %>.associations, 'alias')))).save(); await strapi.hook.bookshelf.manageRelations('<%= id %>', _.merge(_.clone(data.toJSON()), { values })); return data; }, /** * Promise to edit a/an <%= id %>. * * @return {Promise} */ edit: async (params, values) => { 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}); }, /** * Promise to remove a/an <%= id %>. * * @return {Promise} */ remove: (params) => { _.forEach(<%= globalID %>.associations, async association => { await <%= globalID %>.forge(params)[association.alias]().detach(); }); return <%= globalID %>.forge(params).destroy(); } };