Like what we’re doing? Star us on GitHub!

Format the doc response from hooks, only for the API request.

Willy Brownhair
4 weeks ago
1

Hello, I have a question about the capability to format the

doc

response in

afterRead

hook, only on the API request, not when I load the admin. Is there a way to do this?


hooks: {
  afterRead: [
    ({ doc }) => {
      doc.title = doc.title + "foo"
      return doc
    }
  ],
},
In this example, I need to format the

title

only on the api call response. For sur I can create a

customTitle` object key on doc but it's seems to be strange to keep and return unformatted data on the api response. Maybe it's a paradigm problem?



I found a workaround using query param to check "when" the api is called.



hooks: {
    afterRead: [
      ({ doc, req }) => {

        // if "?api" doesn't exist on request URL, return non formatted doc
        if (req.query.api == null)
          return doc

        // with "?api" on api request, we want to get formatted doc
        //ex: http://localhost:3000/api/posts/63f727b53a255a9683223236?api
        // format...

       doc.title = doc.title + "foo"
       console.log("doc.title",doc.title)
       return doc
      }
    ],
  },
Capture_decran_2023-02-23_a_15.38.34.png
Capture_decran_2023-02-23_a_15.39.56.png
    Open the post
    Continue the discussion in Discord
    Can't find what you're looking for?
    Get help straight from the Payload team with an Enterprise License.Learn More