Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda