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] }
I usually just explicitly write
try {
....
return { status: HttpStatus.OK, data: [MyData] }
} catch(e){
return { status: HttpStatus.NOT_FOUND, message: e.message || 'my error' }
}
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