Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
¿Cómo formatear la respuesta por defecto cuando el código de estado es 200 u otro exitoso en NestJS?

¿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] }

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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' } }
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!