Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I usually just explicitly write

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 Denunciar

0

There are many ways for this response but in my opinion, is best practice is to use an interceptor based on 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]};
      }));
  }
}

and in the controller inject the 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');
    }
  }
}

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda