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.

Customize Rest API response in collection hooks

default discord avatar
rk54rk11 months ago
1 2

Hey I'm new to Payload CMS, so I'm trying to implement a comment functionality to a 'comments' collection. Basically everyone is allowed to comment without logging in. So I'd like to add an additional validation: if any user posted a comment within a time interval, the server should respond with an error code to the client side.

I'm stuck on trying to modify the Rest API response in collection hooks. Could someone show me the direction on how to make this work? Thank you! 👏

  hooks: {
    beforeChange: [() => {
      // Check if the commentInterval has passed
      if (Date.now() - lastCommentTimestamp < commentInterval) {

        // How to respond to the client with this error?
        // Just illustrating what I'm trying to do. Apparently this is not going to the client side.
        return Promise.reject({
          message: 'commented too fast!',
          statusCode: 429
        })
      }
    }],
    afterChange: [() => {
      // Update the lastCommentTimestamp
      lastCommentTimestamp = Date.now()
    }]
  }
  • Selected Answer
    discord user avatar
    DanRibbens
    11 months ago

    Hey @rk54rk,

    You can import APIError from 'payload/errors' and instead of return Promise.reject, you'd have throw New APIError(message, 429)

    There are other Error types you can choose from if you wish also.

    I hope that answers your question, let me know if you need anything else!

  • default discord avatar
    rk54rk11 months ago

    Thank you Dan this works perfectly! 👍
    It could be nice to mention API error handling in the docs for anyone who is not familiar with this. All the best with future deveopments for Payload!

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.