fix(content-releases): using lifecycle hooks for delete actions (#19178)

* fix(content-releases): using lifecycle hooks for delete actions when entries are deleted

* Update packages/core/content-releases/server/src/bootstrap.ts

Co-authored-by: markkaylor <mark.kaylor@strapi.io>

---------

Co-authored-by: markkaylor <mark.kaylor@strapi.io>
This commit is contained in:
Fernando Chávez 2024-01-12 16:24:30 +01:00 committed by GitHub
parent 3a85dd153e
commit 6afedafb5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,70 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import type { LoadedStrapi, Entity as StrapiEntity } from '@strapi/types';
import { RELEASE_ACTION_MODEL_UID } from './constants';
const { features } = require('@strapi/strapi/dist/utils/ee');
export const bootstrap = async ({ strapi }: { strapi: LoadedStrapi }) => {
if (
features.isEnabled('cms-content-releases') &&
strapi.features.future.isEnabled('contentReleases')
) {
strapi.db.lifecycles.subscribe({
afterDelete(event) {
// @ts-expect-error TODO: lifecycles types looks like are not 100% finished
const { model, result } = event;
// @ts-expect-error TODO: lifecycles types looks like are not 100% finished
if (model.kind === 'collectionType' && model.options.draftAndPublish) {
const { id } = result;
strapi.db.query(RELEASE_ACTION_MODEL_UID).deleteMany({
where: {
target_type: model.uid,
target_id: id,
},
});
}
},
/**
* deleteMany hook doesn't return the deleted entries ids
* so we need to fetch them before deleting the entries to save the ids on our state
*/
async beforeDeleteMany(event) {
const { model, params } = event;
// @ts-expect-error TODO: lifecycles types looks like are not 100% finished
if (model.kind === 'collectionType' && model.options.draftAndPublish) {
const { where } = params;
const entriesToDelete = await strapi.db
.query(model.uid)
.findMany({ select: ['id'], where });
event.state.entriesToDelete = entriesToDelete;
}
},
/**
* We delete the release actions related to deleted entries
* We make this only after deleteMany is succesfully executed to avoid errors
*/
async afterDeleteMany(event) {
const { model, state } = event;
const entriesToDelete = state.entriesToDelete;
if (entriesToDelete) {
await strapi.db.query(RELEASE_ACTION_MODEL_UID).deleteMany({
where: {
target_type: model.uid,
target_id: {
$in: (entriesToDelete as Array<{ id: StrapiEntity.ID }>).map((entry) => entry.id),
},
},
});
}
},
});
}
};

View File

@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import { register } from './register';
import { bootstrap } from './bootstrap';
import { contentTypes } from './content-types';
import { services } from './services';
import { controllers } from './controllers';
@ -15,6 +16,7 @@ const getPlugin = () => {
) {
return {
register,
bootstrap,
contentTypes,
services,
controllers,