admin管理员组

文章数量:1401849

How to format the response when I got successful response?

For example my code is

 @Get(':id')
  async getOne(@Param('id') id: string) {
    const model = await this.categoriesService.getById(id);
    if (model) {
      return model;
    } else {
      throw new NotFoundException('Category not found');
    }
  }

I got a response is:

{
    "id": 1,
    "name": "test",
    "image": null
}

How to default format to?

{ status: 200|201..., data: [MyData] }

How to format the response when I got successful response?

For example my code is

 @Get(':id')
  async getOne(@Param('id') id: string) {
    const model = await this.categoriesService.getById(id);
    if (model) {
      return model;
    } else {
      throw new NotFoundException('Category not found');
    }
  }

I got a response is:

{
    "id": 1,
    "name": "test",
    "image": null
}

How to default format to?

{ status: 200|201..., data: [MyData] }

Share Improve this question asked May 9, 2022 at 6:20 KhabrKhabr 691 silver badge8 bronze badges 2
  • Is there a reason why you want the status explicitly within the model? Whatever client you're making the request from should give you the status code as part of its request/response interface – Azarro Commented May 9, 2022 at 6:45
  • No I just want to handle errors and responses. For ex default response of erorr is {statusCode: 404, message: "...", error: "Not Found"} I want format it to {status: 404, message: "anyErrorMessage" ?? "Not Found"} P.S. This is a first day when I'm learn nestJS =D – Khabr Commented May 9, 2022 at 6:59
Add a ment  | 

2 Answers 2

Reset to default 5

There are many ways for this response but in my opinion, is best practice is to use an interceptor based on documentation

// src/mon/interceptors/format-response.interceptor.ts

import { CallHandler, ExecutionContext, Injectable, NestInterceptor, HttpStatus  } from '@nestjs/mon';
import { map, Observable } from 'rxjs';

@Injectable()
export class FormatResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(value => {
        value = (value) ? value : []
        return { status: "success", data: [value]};
      }));
  }
}

and in the controller inject the interceptor

import { UseInterceptors } from '@nestjs/mon';

@UseInterceptors(FormatResponseInterceptor)
export class UserController {
    constructor() {}

 @Get(':id')
  async getOne(@Param('id') id: string) {
    const model = await this.categoriesService.getById(id);
    if (model) {
      return model;
    } else {
      throw new NotFoundException('Category not found');
    }
  }
}

And for change the format of error, you can use Filter

I usually just explicitly write

try {
    ....

    return { status: HttpStatus.OK, data: [MyData] }
} catch(e){
    return { status: HttpStatus.NOT_FOUND, message: e.message || 'my error' } 
}

本文标签: