# Breaking Changes
### New file import locations
Exports from the `payload` package have been _significantly_ cleaned up.
Now, just about everything is able to be imported from `payload`
directly, rather than an assortment of subpath exports. This means that
things like `import { buildConfig } from 'payload/config'` are now just
imported via `import { buildConfig } from 'payload'`. The mental model
is significantly simpler for developers, but you might need to update
some of your imports.
Payload now exposes only three exports:
1. `payload` - all types and server-only Payload code
2. `payload/shared` - utilities that can be used in either the browser
or in Node environments
3. `payload/node` - heavy utilities that should only be imported in Node
scripts and never be imported into bundled code like Next.js
### UI library pre-bundling
With this release, we've dramatically sped up the compile time for
Payload by pre-bundling our entire UI package for use inside of the
Payload admin itself. There are new exports that should be used within
Payload custom components:
1. `@payloadcms/ui/client` - all client components
2. `@payloadcms/ui/server` - all server components
For all of your custom Payload admin UI components, you should be
importing from one of these two pre-compiled barrel files rather than
importing from the more deeply nested exports directly. That will keep
compile times nice and speedy, and will also make sure that the bundled
JS for your admin UI is kept small.
For example, whereas before, if you imported the Payload `Button`, you
would have imported it like this:
```ts
import { Button } from '@payloadcms/ui/elements/Button'
```
Now, you would import it like this:
```ts
import { Button } from '@payloadcms/ui/client'
```
This is a significant DX / performance optimization that we're pretty
pumped about.
However, if you are importing or re-using Payload UI components
_outside_ of the Payload admin UI, for example in your own frontend
apps, you can import from the individual component exports which will
make sure that the bundled JS is kept to a minimum in your frontend
apps. So in your own frontend, you can continue to import directly to
the components that you want to consume rather than importing from the
pre-compiled barrel files.
Individual component exports will now come with their corresponding CSS
and everything will work perfectly as-expected.
### Specific exports have changed
- `'@payloadcms/ui/templates/Default'` and
`'@payloadcms/ui/templates/Minimal`' are now exported from
`'@payloadcms/next/templates'`
- Old: `import { LogOut } from '@payloadcms/ui/icons/LogOut'` new:
`import { LogOutIcon } from '@payloadcms/ui/icons/LogOut'`
## Background info
In effort to make local dev as fast as possible, we need to import as
few files as possible so that the compiler has less to process. One way
we've achieved this in the Admin Panel was to _remove_ all .scss imports
from all components in the `@payloadcms/ui` module using a build
process. This stripped all `import './index.scss'` statements out of
each component before injecting them into `dist`. Instead, it bundles
all of the CSS into a single `main.css` file, and we import _that_ at
the root of the app.
While this concept is _still_ the right solution to the problem, this
particular approach is not viable when using these components outside
the Admin Panel, where not only does this root stylesheet not exist, but
where it would also bloat your app with unused styles. Instead, we need
to _keep_ these .scss imports in place so they are imported directly
alongside your components, as expected. Then, we need create a _new_
build step that _separately_ compiles the components _without_ their
stylesheets—this way your app can consume either as needed from the new
`client` and `server` barrel files within `@payloadcms/ui`, i.e. from
within `@payloadcms/next` and all other admin-specific packages and
plugins.
This way, all other applications will simply import using the direct
file paths, just as they did before. Except now they come with
stylesheets.
And we've gotten a pretty awesome initial compilation performance boost.
---------
Co-authored-by: James <james@trbl.design>
Co-authored-by: Alessio Gravili <alessio@gravili.de>
475 lines
15 KiB
TypeScript
475 lines
15 KiB
TypeScript
import type { Payload } from 'payload'
|
|
|
|
import { AuthenticationError } from 'payload'
|
|
|
|
import type { NextRESTClient } from '../helpers/NextRESTClient.js'
|
|
import type { NestedAfterReadHook } from './payload-types.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 configPromise, { HooksConfig } from './config.js'
|
|
import { dataHooksGlobalSlug } from './globals/Data/index.js'
|
|
|
|
let restClient: NextRESTClient
|
|
let payload: Payload
|
|
|
|
describe('Hooks', () => {
|
|
beforeAll(async () => {
|
|
;({ payload, restClient } = await initPayloadInt(configPromise))
|
|
})
|
|
|
|
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', () => {
|
|
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)
|
|
})
|
|
})
|
|
|
|
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" }] })
|
|
})
|
|
})
|
|
})
|