payload icon indicating copy to clipboard operation
payload copied to clipboard

beforeRead and afterRead collection hooks to not modify reponse

Open mortocks opened this issue 1 year ago • 1 comments

Link to reproduction

No response

Payload Version

3.0.0-beta.77

Node Version

v20.15.0

Next.js Version

15.0.0-canary.104

Describe the Bug

When you return a value other that the doc from the beforeRead or afterRead collection hooks, the response is not changes.

I suspect this is something to do with the fact that req is not longer one of the args that the hook provides (which is different from what the docs say). Ideally req would still be an argument you get so you can return req.status but failing that, the value you return should be what's returned in the request

Reproduction Steps

  1. Create collection and add to your payload config
export const Article: CollectionConfig = {
  slug: 'article',
  access: {
    read: () => true,
  },
  hooks: {
    beforeRead: [
      ({ req, doc }) => {
        // doesn't work
        return null
      }
    ],
    afterRead: [
      ({ req, doc }) => {
        // doesn't work
        return null
      }
    ]
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
    }]
}
  1. Curl for that collection

curl http://localhost:3000/api/article

curl http://localhost:3000/api/article/1

The result will be the document or a collection of documents

Adapters and Plugins

db-postgres

mortocks avatar Aug 17 '24 00:08 mortocks

This issue has been marked as stale due to lack of activity.

To keep this issue open, please indicate that it is still relevant in a comment below.

github-actions[bot] avatar Dec 13 '24 05:12 github-actions[bot]

This issue was automatically closed due to lack of activity.

github-actions[bot] avatar Dec 21 '24 05:12 github-actions[bot]

So the "issue" is just that you are returning null and the operations return resultFromHook || result and null is a falsey value so it falls back to the result that was not falsey.

Here is the code that does this: https://github.com/payloadcms/payload/blob/8af8befbd402972d2a40cdc0d51bbec6a53af5d4/packages/payload/src/collections/operations/findByID.ts#L261-L272

You could still return an object that differs from the shape of the document if you wanted to though.

JarrodMFlesch avatar Feb 05 '25 14:02 JarrodMFlesch