admin管理员组文章数量:1401849
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] }
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] }
- Is there a reason why you want the status explicitly within the model? Whatever client you're making the request from should give you the status code as part of its request/response interface – Azarro Commented May 9, 2022 at 6:45
-
No I just want to handle errors and responses. For ex default response of erorr is
{statusCode: 404, message: "...", error: "Not Found"}
I want format it to{status: 404, message: "anyErrorMessage" ?? "Not Found"}
P.S. This is a first day when I'm learn nestJS =D – Khabr Commented May 9, 2022 at 6:59
2 Answers
Reset to default 5There are many ways for this response but in my opinion, is best practice is to use an interceptor
based on documentation
// src/mon/interceptors/format-response.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, HttpStatus } from '@nestjs/mon';
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/mon';
@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
I usually just explicitly write
try {
....
return { status: HttpStatus.OK, data: [MyData] }
} catch(e){
return { status: HttpStatus.NOT_FOUND, message: e.message || 'my error' }
}
本文标签:
版权声明:本文标题:javascript - How to default format response when statusCode is 200 or another successful one in NestJS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744280651a2598633.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论