I'm writing a RESTful API in Nest, which I recently started using and love so far. However, I'm struggling with finding a clean pattern to handle 204 No Content responses for my GET routes. Any recommendations?
I'm a little surprised there isn't something built into the framework for returning 204 if the object returned by a GET controller method is empty -- if there is, I haven't found it yet. If there truly isn't, I'm also wondering if this is worth a feature request on GitHub.
I've tried the following:
- Exposing the Express res property using
@Response()
as a Controller method parameter, then usingres.sendStatus(204)
if the response is empty. However, this requires me to manually send 200 responses too, whereas I'd like to still rely on the framework to handle the request-response cycle and keep my controller methods as clean as possible. - Looked into using an interceptor for checking if the response object is empty, then writing the 204 status code into the response there. I don't really want to do this because the status code could change later due to an exception filter.
- Using middleware to write the response code, but my middleware executes before it gets routed to the controller and I need to check if the response is empty after that. res.on('send') didn't seem to intercept the response on its way out, either.
- Throwing a custom
NoContentException
for my exception filter to handle. Although it's odd to throw an exception for a successful response code, I think this is the way I'll proceed in the meantime since my exception filter is the last thing that will execute in the code I've written.