I'm trying to grasp around the idea of hooks.
I 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.
Is there a tutorial or documentation on how to e.g. execute the CREATE operation on another collection with the use of data from currently edited file?
And Is there a way to execute PUT, DELATE, FIND and other operations directly on Mongo with FETCH, inside hook?
Would appiciate some discussion or help.
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