#Change default Http Code for specific Http Method

9 messages · Page 1 of 1 (latest)

vivid edge
#

Hi,
The default Http Code returned is 201 (Created) for the POST method, and 200 (OK) for all other methods. I want to globally modify the default Http Code returned for a specific method (for example, Delete). How can I do that?
I tried writing this in main.ts:

app.use((req, res, next) => {
    if (req.method === 'DELETE') res.status(204);
    next();
});

But it doesn't work... and no matter how much I search, I can't find a solution...
Is it even possible?

Thank you!

cedar vale
#

The status is applied after the controller handles it, so what you have probably doesn't work because of that.

Maybe you could write an interceptor that uses Reflector to read the the REST method from the handler and then does res.status(xxx).

#

But I'm curious about the use case.

ember tartan
#

Or a custom @Delete()1 decorator that composes the standard @Delete() with the @HttpCode() decorator

cedar vale
vivid edge
#

Oh, I really appreciate the idea of creating a new custom decorator!
Thank you!

And for the use case, it's just that I currently put @HttpCode(HttpStatus.NO_CONTENT) on absolutely all my delete requests, and I'm a bit lazy XD

vivid edge
#

I wrote my decorator, :

export const NoResponseDelete: (path?: string) => MethodDecorator = function (
  path: string,
) {
  return (
    target: object,
    key: string | symbol,
    descriptor: PropertyDescriptor,
  ) => {
    ApiNoContentResponse()(target, key, descriptor);
    Delete(path)(target, key, descriptor);
    HttpCode(HttpStatus.NO_CONTENT)(target, key, descriptor);
  };
};

then use @NoResponseDelete, but Swagger still suggests the codes 200 and 204, whereas if I write it like this

@ApiNoContentResponse()
@Delete()
@HttpCode(HttpStatus.NO_CONTENT)

, it only suggests 204 (as usual)...
Weird, isn't it?
Any idea ?

Thanks !

ember tartan
#

Oh, dude, just use the applyDecorators helper for this.

export const NoResponseDelete = (path?: string) => applyDecorators(
  Delete(path),
  ApiNoContentResponse(),
  HttpCode(HttpStatus.NO_CONTENT)
);
vivid edge
#

I still have the same problem on Swagger, but it's much clearer this way, thanks!!