#Find operation (Local API): context is undefined in hook

8 messages · Page 1 of 1 (latest)

final torrent
#

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:

  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
cold estuaryBOT
final torrent
#

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?

final torrent
#

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.

final torrent
main valve
#

@torn pecan Is 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 😕

torn pecan
main valve
#

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