Hi!
I'm trying to add some context data to a find operation using the Local API. The collection being queried has a beforeRead hook where context is passed in. However, the context is always undefined in the hook.
Given this code to find a document:
const pages = await payload.find({
collection,
where: query,
depth: 2,
limit: 1,
context: {
preview
}
});
And this hook in the collection config:
hooks: {
beforeRead: [
({ doc, context }) => {
console.log(context)
return doc;
}
]
}
The console.log always outputs undefined.
Any idea what I'm doing wrong here? Using Payload v1.15.6
When I log the args parameter in a beforeOperation hook, I can see most of the find operation params, but context is not there. It looks like the context is not actually propagated from the find query object to the hooks. Is this a bug, or intended behavior? If intended, where is context from the find operation actually used?
Did some digging in the Payload source code, and I think can verify that this is a bug:
The context is correctly propagated if I do this:
const pages = await payload.find({
collection,
where: query,
depth: 2,
limit: 1,
req: {} as PayloadRequest
context: {
preview
}
});
And I believe it is because of this code in src/collections/operations/local/find.ts (line 58 in v1.15.6)
export default async function findLocal<T extends keyof GeneratedTypes['collections']>(
payload: Payload,
options: Options<T>,
): Promise<PaginatedDocs<GeneratedTypes['collections'][T]>> {
const {
collection: collectionSlug,
depth,
currentDepth,
page,
limit,
where,
locale = null,
fallbackLocale = null,
user,
overrideAccess = true,
disableErrors,
showHiddenFields,
sort,
draft = false,
pagination = true,
req = {} as PayloadRequest,
context,
} = options;
setRequestContext(options.req, context);
Bug is in the last line (setRequestContext). options.req is null unless passed in. I believe this should be a reference to the req variable instead, as that is the one that is being passed to the find method further down in the code.
Added a pull request in case it helps:
https://github.com/payloadcms/payload/pull/3332Is there any chance this could be looked at? We want to rely on passing context to avoid a recursion issue but this is preventing us from doing so 😕
I'll look into it soon!
Could you verify that it happens on the LATEST 2.0? I remember I fixed some context-related issues recently, maybe that fixed this
Ooop, good call! We were on 2.0.10 and your changes were released in 2.0.12; I will get back to you in a second
It works on 2.0.14! Thanks a bunch and sorry for bothering!
Star
Discord
online
Get dedicated engineering support directly from the Payload team.