Skip to content

Instantly share code, notes, and snippets.

@sdjnes
Created September 4, 2023 10:42
Show Gist options
  • Save sdjnes/6b5a76ae08a6bf8b602e64a0fe6a092c to your computer and use it in GitHub Desktop.
Save sdjnes/6b5a76ae08a6bf8b602e64a0fe6a092c to your computer and use it in GitHub Desktop.
Prevent deletion of in-use resources in Payload
import payload from 'payload';
import { CollectionBeforeDeleteHook } from 'payload/types';
/**
* A very inefficient function to prevent deletion of items when they are referenced in other collections
*
* This should be replaced when Payload implement this feature natively, or provide additional data that we can use
* to implement this more efficiently.
*
* It is on their roadmap (https://github.com/payloadcms/payload/discussions/2938)
*
* @param collectionSlug The collection slug to check for references
* @param displayKey The key to use for the value shown to the user (e.g. 'title' for Pages collection)
* @returns void
* @throws An error containing the names of collection items which contain the ID of the item being saved
*/
function preventDeletionOfUsedItems(
collectionSlug: string,
displayKey: string
): CollectionBeforeDeleteHook {
return async ({ id }) => {
const collectionRequest = await payload.find({
collection: collectionSlug,
limit: Number.MAX_SAFE_INTEGER,
depth: 0,
});
const docs: Array<any> = collectionRequest.docs;
const docsWithReference = docs.reduce((acc, curr) => {
if (JSON.stringify(curr).includes(`${id}`) && (curr as any).id !== id) {
return [
...acc,
{ id: curr.id, title: curr[displayKey] },
];
} else {
return acc;
}
}, []);
throw new Error(
`This item is referenced by ${collectionSlug}: ${docsWithReference
.map((doc) => `"${doc.title}"`)
.join(', ')}`
);
};
}
export { preventDeletionOfUsedItems };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment