当 statusCode 为 200 或 NestJS 中的另一个成功时,如何默认格式化响应?

How to default format response when statusCode is 200 or another successful one in NestJS?

成功响应后如何格式化响应?

例如我的代码是

 @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');
    }
  }

我得到的回复是:

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

如何默认格式化为?

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

我通常直接写

try {
    ....

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

此响应有多种方式,但我认为最佳做法是使用 interceptor 基于 documentation

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

import { CallHandler, ExecutionContext, Injectable, NestInterceptor, HttpStatus  } from '@nestjs/common';
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]};
      }));
  }
}

并在控制器中注入拦截器

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

@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');
    }
  }
}

而要更改错误格式,您可以使用Filter