This PR makes three major changes to the codebase: 1. [Component Paths](#component-paths) Instead of importing custom components into your config directly, they are now defined as file paths and rendered only when needed. That way the Payload config will be significantly more lightweight, and ensures that the Payload config is 100% server-only and Node-safe. Related discussion: https://github.com/payloadcms/payload/discussions/6938 2. [Client Config](#client-config) Deprecates the component map by merging its logic into the client config. The main goal of this change is for performance and simplification. There was no need to deeply iterate over the Payload config twice, once for the component map, and another for the client config. Instead, we can do everything in the client config one time. This has also dramatically simplified the client side prop drilling through the UI library. Now, all components can share the same client config which matches the exact shape of their Payload config (with the exception of non-serializable props and mapped custom components). 3. [Custom client component are no longer server-rendered](#custom-client-components-are-no-longer-server-rendered) Previously, custom components would be server-rendered, no matter if they are server or client components. Now, only server components are rendered on the server. Client components are automatically detected, and simply get passed through as `MappedComponent` to be rendered fully client-side. ## Component Paths Instead of importing custom components into your config directly, they are now defined as file paths and rendered only when needed. That way the Payload config will be significantly more lightweight, and ensures that the Payload config is 100% server-only and Node-safe. Related discussion: https://github.com/payloadcms/payload/discussions/6938 In order to reference any custom components in the Payload config, you now have to specify a string path to the component instead of importing it. Old: ```ts import { MyComponent2} from './MyComponent2.js' admin: { components: { Label: MyComponent2 }, }, ``` New: ```ts admin: { components: { Label: '/collections/Posts/MyComponent2.js#MyComponent2', // <= has to be a relative path based on a baseDir configured in the Payload config - NOT relative based on the importing file }, }, ``` ### Local API within Next.js routes Previously, if you used the Payload Local API within Next.js pages, all the client-side modules are being added to the bundle for that specific page, even if you only need server-side functionality. This `/test` route, which uses the Payload local API, was previously 460 kb. It is now down to 91 kb and does not bundle the Payload client-side admin panel anymore. All tests done [here](https://github.com/payloadcms/payload-3.0-demo/tree/feat/path-test) with beta.67/PR, db-mongodb and default richtext-lexical: **dev /admin before:**  **dev /admin after:**  --- **dev /test before:**  **dev /test after:**  --- **build before:**  **build after::**  ### Usage of the Payload Local API / config outside of Next.js This will make it a lot easier to use the Payload config / local API in other, server-side contexts. Previously, you might encounter errors due to client files (like .scss files) not being allowed to be imported. ## Client Config Deprecates the component map by merging its logic into the client config. The main goal of this change is for performance and simplification. There was no need to deeply iterate over the Payload config twice, once for the component map, and another for the client config. Instead, we can do everything in the client config one time. This has also dramatically simplified the client side prop drilling through the UI library. Now, all components can share the same client config which matches the exact shape of their Payload config (with the exception of non-serializable props and mapped custom components). This is breaking change. The `useComponentMap` hook no longer exists, and most component props have changed (for the better): ```ts const { componentMap } = useComponentMap() // old const { config } = useConfig() // new ``` The `useConfig` hook has also changed in shape, `config` is now a property _within_ the context obj: ```ts const config = useConfig() // old const { config } = useConfig() // new ``` ## Custom Client Components are no longer server rendered Previously, custom components would be server-rendered, no matter if they are server or client components. Now, only server components are rendered on the server. Client components are automatically detected, and simply get passed through as `MappedComponent` to be rendered fully client-side. The benefit of this change: Custom client components can now receive props. Previously, the only way for them to receive dynamic props from a parent client component was to use hooks, e.g. `useFieldProps()`. Now, we do have the option of passing in props to the custom components directly, if they are client components. This will be simpler than having to look for the correct hook. This makes rendering them on the client a little bit more complex, as you now have to check if that component is a server component (=> already has been rendered) or a client component (=> not rendered yet, has to be rendered here). However, this added complexity has been alleviated through the easy-to-use `<RenderMappedComponent />` helper. This helper now also handles rendering arrays of custom components (e.g. beforeList, beforeLogin ...), which actually makes rendering custom components easier in some cases. ## Misc improvements This PR includes misc, breaking changes. For example, we previously allowed unions between components and config object for the same property. E.g. for the custom view property, you were allowed to pass in a custom component or an object with other properties, alongside a custom component. Those union types are now gone. You can now either pass an object, or a component. The previous `{ View: MyViewComponent}` is now `{ View: { Component: MyViewComponent} }` or `{ View: { Default: { Component: MyViewComponent} } }`. This dramatically simplifies the way we read & process those properties, especially in buildComponentMap. We can now simply check for the existence of one specific property, which always has to be a component, instead of running cursed runtime checks on a shared union property which could contain a component, but could also contain functions or objects.   - [x] I have read and understand the [CONTRIBUTING.md](https://github.com/payloadcms/payload/blob/main/CONTRIBUTING.md) document in this repository. --------- Co-authored-by: PatrikKozak <patrik@payloadcms.com> Co-authored-by: Paul <paul@payloadcms.com> Co-authored-by: Paul Popus <paul@nouance.io> Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com> Co-authored-by: James <james@trbl.design>
530 lines
16 KiB
TypeScript
530 lines
16 KiB
TypeScript
import type { Payload } from 'payload'
|
|
|
|
import path from 'path'
|
|
import { AuthenticationError } from 'payload'
|
|
import { fileURLToPath } from 'url'
|
|
|
|
import type { NextRESTClient } from '../helpers/NextRESTClient.js'
|
|
|
|
import { devUser, regularUser } from '../credentials.js'
|
|
import { initPayloadInt } from '../helpers/initPayloadInt.js'
|
|
import { isMongoose } from '../helpers/isMongoose.js'
|
|
import { afterOperationSlug } from './collections/AfterOperation/index.js'
|
|
import { chainingHooksSlug } from './collections/ChainingHooks/index.js'
|
|
import { contextHooksSlug } from './collections/ContextHooks/index.js'
|
|
import { dataHooksSlug } from './collections/Data/index.js'
|
|
import { hooksSlug } from './collections/Hook/index.js'
|
|
import {
|
|
generatedAfterReadText,
|
|
nestedAfterReadHooksSlug,
|
|
} from './collections/NestedAfterReadHooks/index.js'
|
|
import { relationsSlug } from './collections/Relations/index.js'
|
|
import { transformSlug } from './collections/Transform/index.js'
|
|
import { hooksUsersSlug } from './collections/Users/index.js'
|
|
import { HooksConfig } from './config.js'
|
|
import { dataHooksGlobalSlug } from './globals/Data/index.js'
|
|
|
|
let restClient: NextRESTClient
|
|
let payload: Payload
|
|
|
|
const filename = fileURLToPath(import.meta.url)
|
|
const dirname = path.dirname(filename)
|
|
|
|
describe('Hooks', () => {
|
|
beforeAll(async () => {
|
|
;({ payload, restClient } = await initPayloadInt(dirname))
|
|
})
|
|
|
|
afterAll(async () => {
|
|
if (typeof payload.db.destroy === 'function') {
|
|
await payload.db.destroy()
|
|
}
|
|
})
|
|
if (isMongoose(payload)) {
|
|
describe('transform actions', () => {
|
|
it('should create and not throw an error', async () => {
|
|
// the collection has hooks that will cause an error if transform actions is not handled properly
|
|
const doc = await payload.create({
|
|
collection: transformSlug,
|
|
data: {
|
|
localizedTransform: [2, 8],
|
|
transform: [2, 8],
|
|
},
|
|
})
|
|
|
|
expect(doc.transform).toBeDefined()
|
|
expect(doc.localizedTransform).toBeDefined()
|
|
})
|
|
})
|
|
}
|
|
|
|
describe('hook execution', () => {
|
|
let doc
|
|
const data = {
|
|
collectionAfterChange: false,
|
|
collectionAfterRead: false,
|
|
collectionBeforeChange: false,
|
|
collectionBeforeRead: false,
|
|
collectionBeforeValidate: false,
|
|
fieldAfterChange: false,
|
|
fieldAfterRead: false,
|
|
fieldBeforeChange: false,
|
|
fieldBeforeValidate: false,
|
|
}
|
|
beforeEach(async () => {
|
|
doc = await payload.create({
|
|
collection: hooksSlug,
|
|
data,
|
|
})
|
|
})
|
|
|
|
it('should execute hooks in correct order on create', () => {
|
|
expect(doc.collectionAfterChange).toBeTruthy()
|
|
expect(doc.collectionAfterRead).toBeTruthy()
|
|
expect(doc.collectionBeforeChange).toBeTruthy()
|
|
// beforeRead is not run on create operation
|
|
expect(doc.collectionBeforeRead).toBeFalsy()
|
|
expect(doc.collectionBeforeValidate).toBeTruthy()
|
|
expect(doc.fieldAfterChange).toBeTruthy()
|
|
expect(doc.fieldAfterRead).toBeTruthy()
|
|
expect(doc.fieldBeforeChange).toBeTruthy()
|
|
expect(doc.fieldBeforeValidate).toBeTruthy()
|
|
})
|
|
|
|
it('should execute hooks in correct order on update', async () => {
|
|
doc = await payload.update({
|
|
id: doc.id,
|
|
collection: hooksSlug,
|
|
data,
|
|
})
|
|
|
|
expect(doc.collectionAfterChange).toBeTruthy()
|
|
expect(doc.collectionAfterRead).toBeTruthy()
|
|
expect(doc.collectionBeforeChange).toBeTruthy()
|
|
// beforeRead is not run on update operation
|
|
expect(doc.collectionBeforeRead).toBeFalsy()
|
|
expect(doc.collectionBeforeValidate).toBeTruthy()
|
|
expect(doc.fieldAfterChange).toBeTruthy()
|
|
expect(doc.fieldAfterRead).toBeTruthy()
|
|
expect(doc.fieldBeforeChange).toBeTruthy()
|
|
expect(doc.fieldBeforeValidate).toBeTruthy()
|
|
})
|
|
|
|
it('should execute hooks in correct order on find', async () => {
|
|
doc = await payload.findByID({
|
|
id: doc.id,
|
|
collection: hooksSlug,
|
|
})
|
|
|
|
expect(doc.collectionAfterRead).toBeTruthy()
|
|
expect(doc.collectionBeforeRead).toBeTruthy()
|
|
expect(doc.fieldAfterRead).toBeTruthy()
|
|
})
|
|
|
|
it('should save data generated with afterRead hooks in nested field structures', async () => {
|
|
const document = await payload.create({
|
|
collection: nestedAfterReadHooksSlug,
|
|
data: {
|
|
group: {
|
|
array: [{ input: 'input' }],
|
|
},
|
|
text: 'ok',
|
|
},
|
|
})
|
|
|
|
expect(document.group.subGroup.afterRead).toEqual(generatedAfterReadText)
|
|
expect(document.group.array[0].afterRead).toEqual(generatedAfterReadText)
|
|
})
|
|
|
|
it('should populate related docs within nested field structures', async () => {
|
|
const relation = await payload.create({
|
|
collection: relationsSlug,
|
|
data: {
|
|
title: 'Hello',
|
|
},
|
|
})
|
|
|
|
const document = await payload.create({
|
|
collection: nestedAfterReadHooksSlug,
|
|
data: {
|
|
group: {
|
|
array: [
|
|
{
|
|
shouldPopulate: relation.id,
|
|
},
|
|
],
|
|
subGroup: {
|
|
shouldPopulate: relation.id,
|
|
},
|
|
},
|
|
text: 'ok',
|
|
},
|
|
})
|
|
|
|
const retrievedDoc = await payload.findByID({
|
|
id: document.id,
|
|
collection: nestedAfterReadHooksSlug,
|
|
})
|
|
|
|
expect(retrievedDoc.group.array[0].shouldPopulate.title).toEqual(relation.title)
|
|
expect(retrievedDoc.group.subGroup.shouldPopulate.title).toEqual(relation.title)
|
|
})
|
|
|
|
it('should pass result from previous hook into next hook with findByID', async () => {
|
|
const document = await payload.create({
|
|
collection: chainingHooksSlug,
|
|
data: {
|
|
text: 'ok',
|
|
},
|
|
})
|
|
|
|
const retrievedDoc = await payload.findByID({
|
|
id: document.id,
|
|
collection: chainingHooksSlug,
|
|
})
|
|
|
|
expect(retrievedDoc.text).toEqual('ok!!')
|
|
})
|
|
|
|
it('should pass result from previous hook into next hook with find', async () => {
|
|
const document = await payload.create({
|
|
collection: chainingHooksSlug,
|
|
data: {
|
|
text: 'ok',
|
|
},
|
|
})
|
|
|
|
const { docs: retrievedDocs } = await payload.find({
|
|
collection: chainingHooksSlug,
|
|
})
|
|
|
|
expect(retrievedDocs[0].text).toEqual('ok!!')
|
|
})
|
|
|
|
it('should execute collection afterOperation hook', async () => {
|
|
const [doc1, doc2] = await Promise.all([
|
|
await payload.create({
|
|
collection: afterOperationSlug,
|
|
data: {
|
|
title: 'Title',
|
|
},
|
|
}),
|
|
await payload.create({
|
|
collection: afterOperationSlug,
|
|
data: {
|
|
title: 'Title',
|
|
},
|
|
}),
|
|
])
|
|
|
|
expect(doc1.title === 'Title created').toBeTruthy()
|
|
expect(doc2.title === 'Title created').toBeTruthy()
|
|
|
|
const findResult = await payload.find({
|
|
collection: afterOperationSlug,
|
|
})
|
|
|
|
expect(findResult.docs).toHaveLength(2)
|
|
expect(findResult.docs[0].title === 'Title read').toBeTruthy()
|
|
expect(findResult.docs[1].title === 'Title').toBeTruthy()
|
|
|
|
const [updatedDoc1, updatedDoc2] = await Promise.all([
|
|
await payload.update({
|
|
id: doc1.id,
|
|
collection: afterOperationSlug,
|
|
data: {
|
|
title: 'Title',
|
|
},
|
|
}),
|
|
await payload.update({
|
|
id: doc2.id,
|
|
collection: afterOperationSlug,
|
|
data: {
|
|
title: 'Title',
|
|
},
|
|
}),
|
|
])
|
|
|
|
expect(updatedDoc1.title === 'Title updated').toBeTruthy()
|
|
expect(updatedDoc2.title === 'Title updated').toBeTruthy()
|
|
|
|
const findResult2 = await payload.find({
|
|
collection: afterOperationSlug,
|
|
})
|
|
|
|
expect(findResult2.docs).toHaveLength(2)
|
|
expect(findResult2.docs[0].title === 'Title read').toBeTruthy()
|
|
expect(findResult2.docs[1].title === 'Title').toBeTruthy()
|
|
})
|
|
|
|
it('should pass context from beforeChange to afterChange', async () => {
|
|
const document = await payload.create({
|
|
collection: contextHooksSlug,
|
|
data: {
|
|
value: 'wrongvalue',
|
|
},
|
|
})
|
|
|
|
const retrievedDoc = await payload.findByID({
|
|
id: document.id,
|
|
collection: contextHooksSlug,
|
|
})
|
|
|
|
expect(retrievedDoc.value).toEqual('secret')
|
|
})
|
|
|
|
it('should pass context from local API to hooks', async () => {
|
|
const document = await payload.create({
|
|
collection: contextHooksSlug,
|
|
context: {
|
|
secretValue: 'data from local API',
|
|
},
|
|
data: {
|
|
value: 'wrongvalue',
|
|
},
|
|
})
|
|
|
|
const retrievedDoc = await payload.findByID({
|
|
id: document.id,
|
|
collection: contextHooksSlug,
|
|
})
|
|
|
|
expect(retrievedDoc.value).toEqual('data from local API')
|
|
})
|
|
|
|
it('should pass context from local API to global hooks', async () => {
|
|
const globalDocument = await payload.findGlobal({
|
|
slug: dataHooksGlobalSlug,
|
|
})
|
|
|
|
expect(globalDocument.field_globalAndField).not.toEqual('data from local API context')
|
|
|
|
const globalDocumentWithContext = await payload.findGlobal({
|
|
slug: dataHooksGlobalSlug,
|
|
context: {
|
|
field_beforeChange_GlobalAndField_override: 'data from local API context',
|
|
},
|
|
})
|
|
expect(globalDocumentWithContext.field_globalAndField).toEqual('data from local API context')
|
|
})
|
|
|
|
it('should pass context from rest API to hooks', async () => {
|
|
const params = new URLSearchParams({
|
|
context_secretValue: 'data from rest API',
|
|
})
|
|
// send context as query params. It will be parsed by the beforeOperation hook
|
|
const { doc } = await restClient
|
|
.POST(`/${contextHooksSlug}?${params.toString()}`, {
|
|
body: JSON.stringify({
|
|
value: 'wrongvalue',
|
|
}),
|
|
})
|
|
.then((res) => res.json())
|
|
|
|
const retrievedDoc = await payload.findByID({
|
|
collection: contextHooksSlug,
|
|
id: doc.id,
|
|
})
|
|
|
|
expect(retrievedDoc.value).toEqual('data from rest API')
|
|
})
|
|
})
|
|
|
|
describe('auth collection hooks', () => {
|
|
let hookUser
|
|
let hookUserToken
|
|
|
|
beforeAll(async () => {
|
|
const email = 'dontrefresh@payloadcms.com'
|
|
|
|
hookUser = await payload.create({
|
|
collection: hooksUsersSlug,
|
|
data: {
|
|
email,
|
|
password: devUser.password,
|
|
roles: ['admin'],
|
|
},
|
|
})
|
|
|
|
const { token } = await payload.login({
|
|
collection: hooksUsersSlug,
|
|
data: {
|
|
email: hookUser.email,
|
|
password: devUser.password,
|
|
},
|
|
})
|
|
|
|
hookUserToken = token
|
|
})
|
|
|
|
it('should call afterLogin hook', async () => {
|
|
const { user } = await payload.login({
|
|
collection: hooksUsersSlug,
|
|
data: {
|
|
email: devUser.email,
|
|
password: devUser.password,
|
|
},
|
|
})
|
|
|
|
const result = await payload.findByID({
|
|
id: user.id,
|
|
collection: hooksUsersSlug,
|
|
})
|
|
|
|
expect(user).toBeDefined()
|
|
expect(user.afterLoginHook).toStrictEqual(true)
|
|
expect(result.afterLoginHook).toStrictEqual(true)
|
|
})
|
|
|
|
it('deny user login', async () => {
|
|
await expect(() =>
|
|
payload.login({
|
|
collection: hooksUsersSlug,
|
|
data: { email: regularUser.email, password: regularUser.password },
|
|
}),
|
|
).rejects.toThrow(AuthenticationError)
|
|
})
|
|
|
|
it('should respect refresh hooks', async () => {
|
|
const response = await restClient.POST(`/${hooksUsersSlug}/refresh-token`, {
|
|
headers: {
|
|
Authorization: `JWT ${hookUserToken}`,
|
|
},
|
|
})
|
|
|
|
const data = await response.json()
|
|
|
|
expect(data.exp).toStrictEqual(1)
|
|
expect(data.refreshedToken).toStrictEqual('fake')
|
|
})
|
|
|
|
it('should respect me hooks', async () => {
|
|
const response = await restClient.GET(`/${hooksUsersSlug}/me`, {
|
|
headers: {
|
|
Authorization: `JWT ${hookUserToken}`,
|
|
},
|
|
})
|
|
|
|
const data = await response.json()
|
|
|
|
expect(data.exp).toStrictEqual(10000)
|
|
})
|
|
})
|
|
|
|
describe('hook parameter data', () => {
|
|
it('should pass collection prop to collection hooks', async () => {
|
|
const sanitizedConfig = await HooksConfig
|
|
const sanitizedHooksCollection = JSON.parse(
|
|
JSON.stringify(sanitizedConfig.collections.find(({ slug }) => slug === dataHooksSlug)),
|
|
)
|
|
|
|
const doc = await payload.create({
|
|
collection: dataHooksSlug,
|
|
data: {},
|
|
})
|
|
|
|
expect(JSON.parse(doc.collection_beforeOperation_collection)).toStrictEqual(
|
|
sanitizedHooksCollection,
|
|
)
|
|
expect(JSON.parse(doc.collection_beforeChange_collection)).toStrictEqual(
|
|
sanitizedHooksCollection,
|
|
)
|
|
expect(JSON.parse(doc.collection_afterChange_collection)).toStrictEqual(
|
|
sanitizedHooksCollection,
|
|
)
|
|
expect(JSON.parse(doc.collection_afterRead_collection)).toStrictEqual(
|
|
sanitizedHooksCollection,
|
|
)
|
|
expect(JSON.parse(doc.collection_afterOperation_collection)).toStrictEqual(
|
|
sanitizedHooksCollection,
|
|
)
|
|
|
|
// BeforeRead is only run for find operations
|
|
const foundDoc = await payload.findByID({
|
|
id: doc.id,
|
|
collection: dataHooksSlug,
|
|
})
|
|
|
|
expect(JSON.parse(foundDoc.collection_beforeRead_collection)).toStrictEqual(
|
|
sanitizedHooksCollection,
|
|
)
|
|
})
|
|
|
|
it('should pass collection and field props to field hooks', async () => {
|
|
const sanitizedConfig = await HooksConfig
|
|
const sanitizedHooksCollection = sanitizedConfig.collections.find(
|
|
({ slug }) => slug === dataHooksSlug,
|
|
)
|
|
|
|
const field = sanitizedHooksCollection.fields.find(
|
|
(field) => 'name' in field && field.name === 'field_collectionAndField',
|
|
)
|
|
|
|
const doc = await payload.create({
|
|
collection: dataHooksSlug,
|
|
data: {},
|
|
})
|
|
|
|
const collectionAndField = JSON.stringify(sanitizedHooksCollection) + JSON.stringify(field)
|
|
|
|
expect(doc.field_collectionAndField).toStrictEqual(collectionAndField + collectionAndField)
|
|
})
|
|
|
|
it('should pass global prop to global hooks', async () => {
|
|
const sanitizedConfig = await HooksConfig
|
|
const sanitizedHooksGlobal = JSON.parse(
|
|
JSON.stringify(sanitizedConfig.globals.find(({ slug }) => slug === dataHooksGlobalSlug)),
|
|
)
|
|
|
|
const doc = await payload.updateGlobal({
|
|
slug: dataHooksGlobalSlug,
|
|
data: {},
|
|
})
|
|
|
|
expect(JSON.parse(doc.global_beforeChange_global)).toStrictEqual(sanitizedHooksGlobal)
|
|
expect(JSON.parse(doc.global_afterRead_global)).toStrictEqual(sanitizedHooksGlobal)
|
|
expect(JSON.parse(doc.global_afterChange_global)).toStrictEqual(sanitizedHooksGlobal)
|
|
|
|
// beforeRead is only run for findOne operations
|
|
const foundDoc = await payload.findGlobal({
|
|
slug: dataHooksGlobalSlug,
|
|
})
|
|
|
|
expect(JSON.parse(foundDoc.global_beforeRead_global)).toStrictEqual(sanitizedHooksGlobal)
|
|
})
|
|
|
|
it('should pass global and field props to global hooks', async () => {
|
|
const sanitizedConfig = await HooksConfig
|
|
const sanitizedHooksGlobal = sanitizedConfig.globals.find(
|
|
({ slug }) => slug === dataHooksGlobalSlug,
|
|
)
|
|
|
|
const globalString = JSON.stringify(sanitizedHooksGlobal)
|
|
|
|
const fieldString = JSON.stringify(
|
|
sanitizedHooksGlobal.fields.find(
|
|
(field) => 'name' in field && field.name === 'field_globalAndField',
|
|
),
|
|
)
|
|
|
|
const doc = await payload.updateGlobal({
|
|
slug: dataHooksGlobalSlug,
|
|
data: {},
|
|
})
|
|
|
|
const globalAndFieldString = globalString + fieldString
|
|
|
|
expect(doc.field_globalAndField).toStrictEqual(globalAndFieldString + globalAndFieldString)
|
|
})
|
|
})
|
|
|
|
describe('config level after error hook', () => {
|
|
it('should handle error', async () => {
|
|
const response = await restClient.GET(`/throw-to-after-error`, {})
|
|
const body = await response.json()
|
|
expect(response.status).toEqual(418)
|
|
expect(body).toEqual({ errors: [{ message: "I'm a teapot" }] })
|
|
})
|
|
})
|
|
})
|