feat: ability to add context to payload's request object (#2796)
Co-authored-by: Dan Ribbens <dan.ribbens@gmail.com>
This commit is contained in:
@@ -12,13 +12,16 @@ import type { NestedAfterReadHook } from './payload-types';
|
||||
import { hooksUsersSlug } from './collections/Users';
|
||||
import { devUser, regularUser } from '../credentials';
|
||||
import { AuthenticationError } from '../../src/errors';
|
||||
import { contextHooksSlug } from './collections/ContextHooks';
|
||||
|
||||
let client: RESTClient;
|
||||
let apiUrl;
|
||||
|
||||
describe('Hooks', () => {
|
||||
beforeAll(async () => {
|
||||
const { serverURL } = await initPayloadTest({ __dirname, init: { local: false } });
|
||||
client = new RESTClient(config, { serverURL, defaultSlug: transformSlug });
|
||||
apiUrl = `${serverURL}/api`;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -151,6 +154,63 @@ describe('Hooks', () => {
|
||||
|
||||
expect(retrievedDocs[0].text).toEqual('ok!!');
|
||||
});
|
||||
|
||||
it('should pass context from beforeChange to afterChange', async () => {
|
||||
const document = await payload.create({
|
||||
collection: contextHooksSlug,
|
||||
data: {
|
||||
value: 'wrongvalue',
|
||||
},
|
||||
});
|
||||
|
||||
const retrievedDoc = await payload.findByID({
|
||||
collection: contextHooksSlug,
|
||||
id: document.id,
|
||||
});
|
||||
|
||||
expect(retrievedDoc.value).toEqual('secret');
|
||||
});
|
||||
|
||||
it('should pass context from local API to hooks', async () => {
|
||||
const document = await payload.create({
|
||||
collection: contextHooksSlug,
|
||||
data: {
|
||||
value: 'wrongvalue',
|
||||
},
|
||||
context: {
|
||||
secretValue: 'data from local API',
|
||||
},
|
||||
});
|
||||
|
||||
const retrievedDoc = await payload.findByID({
|
||||
collection: contextHooksSlug,
|
||||
id: document.id,
|
||||
});
|
||||
|
||||
expect(retrievedDoc.value).toEqual('data from local API');
|
||||
});
|
||||
|
||||
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 response = await fetch(`${apiUrl}/${contextHooksSlug}?${params.toString()}`, {
|
||||
body: JSON.stringify({
|
||||
value: 'wrongvalue',
|
||||
}),
|
||||
method: 'post',
|
||||
});
|
||||
|
||||
const document = (await response.json()).doc;
|
||||
|
||||
const retrievedDoc = await payload.findByID({
|
||||
collection: contextHooksSlug,
|
||||
id: document.id,
|
||||
});
|
||||
|
||||
expect(retrievedDoc.value).toEqual('data from rest API');
|
||||
});
|
||||
});
|
||||
|
||||
describe('auth collection hooks', () => {
|
||||
|
||||
Reference in New Issue
Block a user