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()
}]
}
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!
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
Discord
online
Get dedicated engineering support directly from the Payload team.