Files
payloadcms/test/hooks/globals/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

98 lines
2.4 KiB
TypeScript

/* eslint-disable no-param-reassign */
import type { GlobalConfig } from '../../../../packages/payload/src/globals/config/types'
export const dataHooksGlobalSlug = 'data-hooks-global'
export const DataHooksGlobal: GlobalConfig = {
slug: dataHooksGlobalSlug,
access: {
read: () => true,
update: () => true,
},
hooks: {
beforeChange: [
({ data, global, context }) => {
context['global_beforeChange_global'] = JSON.stringify(global)
return data
},
],
beforeRead: [
async ({ context, global }) => {
context['global_beforeRead_global'] = JSON.stringify(global)
},
],
afterRead: [
({ context, global, doc }) => {
context['global_afterRead_global'] = JSON.stringify(global)
// Needs to be done for both afterRead (for findOne test) and afterChange (for update test)
for (const contextKey in context) {
if (contextKey.startsWith('global_')) {
doc[contextKey] = context[contextKey]
}
}
return doc
},
],
afterChange: [
async ({ context, global, doc }) => {
context['global_afterChange_global'] = JSON.stringify(global)
// Needs to be done for both afterRead (for findOne test) and afterChange (for update test), as afterChange is called after afterRead
for (const contextKey in context) {
if (contextKey.startsWith('global_')) {
doc[contextKey] = context[contextKey]
}
}
return doc
},
],
},
fields: [
{
name: 'field_globalAndField',
type: 'text',
hooks: {
beforeChange: [
({ global, field, context, value }) => {
context['field_beforeChange_GlobalAndField'] =
JSON.stringify(global) + JSON.stringify(field)
return value
},
],
afterRead: [
({ global, field, context }) => {
return (
(context['field_beforeChange_GlobalAndField'] as string) +
JSON.stringify(global) +
JSON.stringify(field)
)
},
],
},
},
{
name: 'global_beforeChange_global',
type: 'text',
},
{
name: 'global_afterChange_global',
type: 'text',
},
{
name: 'global_beforeRead_global',
type: 'text',
},
{
name: 'global_afterRead_global',
type: 'text',
},
],
}