Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

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

default discord avatar
Willy Brownhair2 years 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
      }
    ],
  },
    Star on GitHub

    Star

    Chat on Discord

    Discord

    online

    Can't find what you're looking for?

    Get dedicated engineering support directly from the Payload team.