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

282
Views
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 answers
Answer question

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 Report

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 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!