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:
Alessio Gravili
2023-07-26 15:07:49 +02:00
committed by GitHub
parent cf9795b8d8
commit 67ba131cc6
63 changed files with 570 additions and 40 deletions

View File

@@ -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', () => {