Home > Net >  How to make custom response in Nestjs?
How to make custom response in Nestjs?

Time:11-22

I need custom response to all my controllers, how to make this real?

I have format like this: Success response

{
  status: string,
  code: number,
  message: string
  data: object | array | any,
  request: {
    url: string,
    method: string
  }
}

Exception response

{
  status: string,
  code: number,
  message: string
  error: object | array | any,
  request: {
    url: string,
    method: string
  }
}

How can I implement it in Nestjs?

CodePudding user response:

Inside the controller function you can just return your objects:

@Get('path')
async getResponse() {
  if(success) {
    return {
      status: string,
      code: number,
      message: string
      data: object | array | any,
      request: {
        url: string,
        method: string
      }
  } else if (error) {
    return {
      status: string,
      code: number,
      message: string
      error: object | array | any,
      request: {
        url: string,
        method: string
      }
    }
  }

Alternatively, you can also use the expressjs Reponse and Request objects as described in the docs.

If you want to make use of type safety, you can specify your response types in another file, like so:

response.interface.ts

export interface SuccessResponse = {
  status: string,
  code: number,
  message: string
  data: object | array | any,
  request: {
    url: string,
    method: string
  }
}

export type ErrorResponse = {
  status: string,
  code: number,
  message: string
  error: object | array | any,
  request: {
    url: string,
    method: string
  }
}

And then in your controller:

@Get('path')
async getResponse(): SuccessResponse | ErrorResponse { ... }

CodePudding user response:

I would create an interceptor that does some response mapping for you so that you can just return the data and the interceptor can format it for all endpoints. For exceptions, I would create an explicit exception filter that does something similar. Both of these should have access to the ArgumentHost/ExecutionContext which can be used to get the request and response object so you have access to things like the url and method, the current status code, and whatever else you may need.

  • Related