¿Cómo formatear la respuesta cuando obtuve una respuesta exitosa?
Por ejemplo mi código es
@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'); } }Tengo una respuesta es:
{ "id": 1, "name": "test", "image": null }¿Cómo formatear por defecto?
{ status: 200|201..., data: [MyData] }
Por lo general, solo escribo explícitamente
try { .... return { status: HttpStatus.OK, data: [MyData] } } catch(e){ return { status: HttpStatus.NOT_FOUND, message: e.message || 'my error' } }Hay muchas maneras para esta respuesta, pero en mi opinión, la mejor práctica es usar un interceptor basado en la documentación .
// 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]}; })); } }y en el controlador inyectar el interceptor
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'); } } }Y para cambiar el formato de error, puede usar Filter