-
I'm trying to grasp around the idea of hooks. PROBLEMI need to create a hook that allows Admin to duplicate file after it has been reviewed to another collection, and delate the one he has reviewed. IDEAAnd Is there a way to execute PUT, DELATE, FIND and other operations directly on Mongo with FETCH, inside hook? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey @quornik, this is definitely possible by combining the use of a beforeChange hook and the local API operations. Here is an example of how it can be done: import { CollectionBeforeChangeHook, CollectionConfig } from 'payload/types'
const performOperationIfReviewed: CollectionBeforeChangeHook = async ({
data, // incoming data to update or create with
req, // full express request
operation, // name of the operation ie. 'create', 'update'
originalDoc, // original document
}) => {
if (
req?.user?.collection === 'admins' && // Admins collection only
operation === 'update' && // Only on update operations
!originalDoc.reviewed && data.reviewed // Transitioning from not reviewed to reviewed
) {
await req.payload.create({
collection: 'collection-after-reviewed',
data,
})
}
}
export const Pages: CollectionConfig = {
slug: 'pages',
hooks: {
beforeChange: [performOperationIfReviewed],
},
fields: [
{
name: 'reviewFile',
type: 'relationship',
relationTo: 'media',
},
{
name: 'reviewed',
type: 'checkbox',
}
],
} Hopefully, that gets you going in the right direction. Let me know if you have any additional questions 👍 |
Beta Was this translation helpful? Give feedback.
Hey @quornik, this is definitely possible by combining the use of a beforeChange hook and the local API operations.
Here is an example of how it can be done: