310 lines
8.9 KiB
JavaScript
Raw Normal View History

'use strict';
2022-10-05 18:42:50 +02:00
const { assoc, has, prop, omit } = require('lodash/fp');
2021-04-29 13:51:12 +02:00
const strapiUtils = require('@strapi/utils');
const { mapAsync } = require('@strapi/utils');
2021-10-20 17:30:05 +02:00
const { ApplicationError } = require('@strapi/utils').errors;
2022-10-05 18:42:50 +02:00
const { getDeepPopulate, getDeepPopulateDraftCount } = require('./utils/populate');
const { getDeepRelationsCount } = require('./utils/count');
2022-10-05 18:42:50 +02:00
const { sumDraftCounts } = require('./utils/draft');
2022-10-05 18:42:50 +02:00
const { hasDraftAndPublish } = strapiUtils.contentTypes;
const { PUBLISHED_AT_ATTRIBUTE, CREATED_BY_ATTRIBUTE } = strapiUtils.contentTypes.constants;
const { ENTRY_PUBLISH, ENTRY_UNPUBLISH } = strapiUtils.webhook.webhookEvents;
const omitPublishedAtField = omit(PUBLISHED_AT_ATTRIBUTE);
2023-01-30 16:35:45 +01:00
const emitEvent = async (event, entity, modelUid) => {
const modelDef = strapi.getModel(modelUid);
2021-11-10 17:08:54 +01:00
const sanitizedEntity = await strapiUtils.sanitize.sanitizers.defaultSanitizeOutput(
modelDef,
entity
);
strapi.eventHub.emit(event, {
model: modelDef.modelName,
entry: sanitizedEntity,
});
};
2022-08-08 23:33:39 +02:00
const findCreatorRoles = (entity) => {
const createdByPath = `${CREATED_BY_ATTRIBUTE}.id`;
if (has(createdByPath, entity)) {
const creatorId = prop(createdByPath, entity);
return strapi.query('admin::role').findMany({ where: { users: { id: creatorId } } });
}
return [];
};
2022-08-08 23:33:39 +02:00
const addCreatedByRolesPopulate = (populate) => {
2021-09-24 15:40:02 +02:00
return {
...populate,
createdBy: {
populate: ['roles'],
},
};
};
/**
2023-01-19 15:14:48 +01:00
* When webhooks.populateRelations is set to true, populated relations
* will be passed to any webhook event. The entity-manager
* response will not have the populated relations though.
* For performance reasons, it is recommended to set it to false,
*
2023-01-23 10:49:31 +01:00
* TODO V5: Set to false by default.
* TODO V5: Make webhooks always send the same entity data.
*/
const isRelationsPopulateEnabled = () => {
return strapi.config.get('server.webhooks.populateRelations', true);
};
/**
* @type {import('./entity-manager').default}
*/
2021-07-13 18:46:36 +02:00
module.exports = ({ strapi }) => ({
async assocCreatorRoles(entity) {
if (!entity) {
return entity;
}
const roles = await findCreatorRoles(entity);
return assoc(`${CREATED_BY_ATTRIBUTE}.roles`, roles, entity);
},
/**
* Extend this function from other plugins to add custom mapping of entity
* responses
* @param {Object} entity
* @returns
*/
mapEntity(entity) {
return entity;
},
2023-02-27 11:50:49 +00:00
/**
2023-03-01 11:31:52 +00:00
* Some entity manager functions may return multiple entities or one entity.
2023-02-27 11:50:49 +00:00
* This function maps the response in both cases
* @param {Array|Object|null} entities
* @param {string} uid
*/
2023-03-01 11:31:52 +00:00
async mapEntitiesResponse(entities, uid) {
2023-02-27 11:50:49 +00:00
if (entities?.results) {
const mappedResults = await mapAsync(entities.results, (entity) =>
this.mapEntity(entity, uid)
);
return { ...entities, results: mappedResults };
}
// if entity is single type
return this.mapEntity(entities, uid);
},
async find(opts, uid) {
const params = { ...opts, populate: getDeepPopulate(uid) };
2021-06-30 20:00:03 +02:00
const entities = await strapi.entityService.findMany(uid, params);
2023-02-13 17:39:51 +01:00
2023-03-01 11:31:52 +00:00
return this.mapEntitiesResponse(entities, uid);
},
async findPage(opts, uid) {
const params = { ...opts, populate: getDeepPopulate(uid, { maxLevel: 1 }) };
2021-06-30 20:00:03 +02:00
const entities = await strapi.entityService.findPage(uid, params);
2023-02-13 17:39:51 +01:00
2023-03-01 11:31:52 +00:00
return this.mapEntitiesResponse(entities, uid);
},
async findWithRelationCountsPage(opts, uid) {
const counterPopulate = getDeepPopulate(uid, { countMany: true, maxLevel: 1 });
2022-08-26 10:41:31 +02:00
const params = { ...opts, populate: addCreatedByRolesPopulate(counterPopulate) };
2021-06-30 20:00:03 +02:00
const entities = await strapi.entityService.findWithRelationCountsPage(uid, params);
2023-03-01 11:31:52 +00:00
return this.mapEntitiesResponse(entities, uid);
2020-12-16 15:28:11 +01:00
},
async findOneWithCreatorRolesAndCount(id, uid) {
const counterPopulate = getDeepPopulate(uid, { countMany: true, countOne: true });
2022-08-26 10:41:31 +02:00
const params = { populate: addCreatedByRolesPopulate(counterPopulate) };
return strapi.entityService
.findOne(uid, id, params)
.then((entity) => this.mapEntity(entity, uid));
2022-08-26 10:41:31 +02:00
},
async findOne(id, uid) {
const params = { populate: getDeepPopulate(uid) };
2021-07-08 18:15:32 +02:00
return strapi.entityService
.findOne(uid, id, params)
.then((entity) => this.mapEntity(entity, uid));
},
async findOneWithCreatorRoles(id, uid) {
const entity = await this.findOne(id, uid).then((entity) => this.mapEntity(entity, uid));
if (!entity) {
return entity;
}
return this.assocCreatorRoles(entity);
},
2021-06-30 20:00:03 +02:00
async create(body, uid) {
const modelDef = strapi.getModel(uid);
const publishData = { ...body };
const populateRelations = isRelationsPopulateEnabled(uid);
if (hasDraftAndPublish(modelDef)) {
publishData[PUBLISHED_AT_ATTRIBUTE] = null;
}
const params = {
data: publishData,
2023-01-26 17:25:56 +01:00
populate: populateRelations
? getDeepPopulate(uid, {})
: getDeepPopulate(uid, { countMany: true, countOne: true }),
};
2021-07-08 18:15:32 +02:00
const entity = await strapi.entityService
.create(uid, params)
.then((entity) => this.mapEntity(entity, uid));
2023-01-26 17:25:56 +01:00
// If relations were populated, relations count will be returned instead of the array of relations.
if (populateRelations) {
return getDeepRelationsCount(entity, uid);
}
2023-02-14 18:20:16 +01:00
return entity;
},
async update(entity, body, uid) {
const publishData = omitPublishedAtField(body);
const populateRelations = isRelationsPopulateEnabled(uid);
const params = {
data: publishData,
2023-01-26 17:25:56 +01:00
populate: populateRelations
? getDeepPopulate(uid, {})
: getDeepPopulate(uid, { countMany: true, countOne: true }),
};
2021-07-08 18:15:32 +02:00
const updatedEntity = await strapi.entityService
.update(uid, entity.id, params)
.then((entity) => this.mapEntity(entity, uid));
2023-01-30 16:35:45 +01:00
// If relations were populated, relations count will be returned instead of the array of relations.
if (populateRelations) {
return getDeepRelationsCount(updatedEntity, uid);
}
return updatedEntity;
},
async delete(entity, uid) {
const populateRelations = isRelationsPopulateEnabled(uid);
const params = {
2023-01-26 17:25:56 +01:00
populate: populateRelations
? getDeepPopulate(uid, {})
: getDeepPopulate(uid, { countMany: true, countOne: true }),
};
const deletedEntity = await strapi.entityService.delete(uid, entity.id, params);
2023-01-30 16:35:45 +01:00
// If relations were populated, relations count will be returned instead of the array of relations.
if (populateRelations) {
return getDeepRelationsCount(deletedEntity, uid);
}
return deletedEntity;
},
2021-07-08 18:15:32 +02:00
// FIXME: handle relations
2021-07-05 23:31:23 +02:00
deleteMany(opts, uid) {
2021-06-30 20:00:03 +02:00
const params = { ...opts };
return strapi.entityService.deleteMany(uid, params);
},
2023-01-30 16:35:45 +01:00
async publish(entity, body = {}, uid) {
if (entity[PUBLISHED_AT_ATTRIBUTE]) {
2021-10-20 17:30:05 +02:00
throw new ApplicationError('already.published');
}
// validate the entity is valid for publication
await strapi.entityValidator.validateEntityCreation(
strapi.getModel(uid),
entity,
undefined,
entity
);
const data = { ...body, [PUBLISHED_AT_ATTRIBUTE]: new Date() };
const populateRelations = isRelationsPopulateEnabled(uid);
const params = {
data,
2023-01-26 17:25:56 +01:00
populate: populateRelations
? getDeepPopulate(uid, {})
: getDeepPopulate(uid, { countMany: true, countOne: true }),
};
2021-07-08 18:15:32 +02:00
2023-01-30 16:35:45 +01:00
const updatedEntity = await strapi.entityService.update(uid, entity.id, params);
2023-03-03 14:02:56 +01:00
await emitEvent(ENTRY_PUBLISH, updatedEntity, uid);
2023-01-30 16:35:45 +01:00
const mappedEntity = await this.mapEntity(updatedEntity, uid);
2023-01-30 16:35:45 +01:00
// If relations were populated, relations count will be returned instead of the array of relations.
if (isRelationsPopulateEnabled(uid)) {
return getDeepRelationsCount(mappedEntity, uid);
2023-01-30 16:35:45 +01:00
}
return mappedEntity;
2023-01-30 16:35:45 +01:00
},
2023-01-30 16:35:45 +01:00
async unpublish(entity, body = {}, uid) {
if (!entity[PUBLISHED_AT_ATTRIBUTE]) {
2021-10-20 17:30:05 +02:00
throw new ApplicationError('already.draft');
}
const data = { ...body, [PUBLISHED_AT_ATTRIBUTE]: null };
const populateRelations = isRelationsPopulateEnabled(uid);
const params = {
data,
2023-01-26 17:25:56 +01:00
populate: populateRelations
? getDeepPopulate(uid, {})
: getDeepPopulate(uid, { countMany: true, countOne: true }),
};
2021-07-08 18:15:32 +02:00
2023-01-30 16:35:45 +01:00
const updatedEntity = await strapi.entityService.update(uid, entity.id, params);
await emitEvent(ENTRY_UNPUBLISH, updatedEntity, uid);
2023-01-30 16:35:45 +01:00
const mappedEntity = await this.mapEntity(updatedEntity, uid);
2023-01-30 16:35:45 +01:00
// If relations were populated, relations count will be returned instead of the array of relations.
if (isRelationsPopulateEnabled(uid)) {
return getDeepRelationsCount(mappedEntity, uid);
2023-01-30 16:35:45 +01:00
}
return mappedEntity;
2023-01-30 16:35:45 +01:00
},
2022-10-05 18:42:50 +02:00
async getNumberOfDraftRelations(id, uid) {
const { populate, hasRelations } = getDeepPopulateDraftCount(uid);
if (!hasRelations) {
return 0;
}
const entity = await strapi.entityService.findOne(uid, id, { populate });
return sumDraftCounts(entity, uid);
},
2021-07-13 18:46:36 +02:00
});