Files
payload/test/hooks/collections/Data/index.ts
Alessio Gravili f6adbae0c7 feat: collection, global and field props for hooks, fix request context initialization, add context to global hooks (#3780)
* feat: pass collection, global and field props to collection, global and field hooks - where applicable

* fix: initial request context not set for all operations

* chore: add tests which check the collection prop for collection hooks

* feat: add context to props of global hooks

* chore: add global tests for global and field props

* chore: int tests: use JSON instead of object hashes
2023-10-21 11:40:57 +02:00

112 lines
2.7 KiB
TypeScript

/* eslint-disable no-param-reassign */
import type { CollectionConfig } from '../../../../packages/payload/src/collections/config/types'
export const dataHooksSlug = 'data-hooks'
export const DataHooks: CollectionConfig = {
slug: dataHooksSlug,
access: {
read: () => true,
create: () => true,
delete: () => true,
update: () => true,
},
hooks: {
beforeOperation: [
async ({ context, collection, args }) => {
context['collection_beforeOperation_collection'] = JSON.stringify(collection)
return args
},
],
beforeChange: [
({ context, data, collection }) => {
context['collection_beforeChange_collection'] = JSON.stringify(collection)
return data
},
],
afterChange: [
async ({ context, collection }) => {
context['collection_afterChange_collection'] = JSON.stringify(collection)
},
],
beforeRead: [
async ({ context, collection }) => {
context['collection_beforeRead_collection'] = JSON.stringify(collection)
},
],
afterRead: [
({ context, collection, doc }) => {
context['collection_afterRead_collection'] = JSON.stringify(collection)
return doc
},
],
afterOperation: [
({ args, result, collection }) => {
args.req.context['collection_afterOperation_collection'] = JSON.stringify(collection)
for (const contextKey in args.req.context) {
if (contextKey.startsWith('collection_')) {
result[contextKey] = args.req.context[contextKey]
}
}
return result
},
],
},
fields: [
{
name: 'field_collectionAndField',
type: 'text',
hooks: {
beforeChange: [
({ collection, field, context, value }) => {
context['field_beforeChange_CollectionAndField'] =
JSON.stringify(collection) + JSON.stringify(field)
return value
},
],
afterRead: [
({ collection, field, context }) => {
return (
(context['field_beforeChange_CollectionAndField'] as string) +
JSON.stringify(collection) +
JSON.stringify(field)
)
},
],
},
},
{
name: 'collection_beforeOperation_collection',
type: 'text',
},
{
name: 'collection_beforeChange_collection',
type: 'text',
},
{
name: 'collection_afterChange_collection',
type: 'text',
},
{
name: 'collection_beforeRead_collection',
type: 'text',
},
{
name: 'collection_afterRead_collection',
type: 'text',
},
{
name: 'collection_afterOperation_collection',
type: 'text',
},
],
}