[英]How to create Nest JS API response format common for each API?
我是 nestjs 的新手,一直堅持為所有 API 制作一個通用的響應主體。 目前,我正在使用 map 從集合中獲取響應,但不知道如何以下面提到的方式格式化響應。
我目前正在收到如下響應正文 -
Response body
[
{
"userId": "602a0f175bbd45688cd001f4",
"firstName": "Gagan",
"lastName": "Pandya",
"email": "gagankumar.pandya@galaxyweblinks.in",
"status": "active"
},
{
"userId": "603f3b547508bbd77a3d6fb5",
"firstName": "Kunal",
"lastName": "Ghosh",
"email": "kunal.ghosh@galaxyweblinks.in",
"status": "active"
}
]
需要將其設置為-
{
"statusCode": 200,
"message": "User Listing",
"data":[
{
"userId": "602a0f175bbd45688cd001f4",
"firstName": "Gagan",
"lastName": "Pandya",
"email": "gagankumar.pandya@galaxyweblinks.in",
"status": "active"
},
{
"userId": "603f3b547508bbd77a3d6fb5",
"firstName": "Kunal",
"lastName": "Ghosh",
"email": "kunal.ghosh@galaxyweblinks.in",
"status": "active"
}
]
}
下面是我的 controller 代碼 -
@Get('/users-listing')
// @UseGuards(AuthGuard('jwt'))
// @Roles('Super Admin')
@ApiOperation({ title: 'Lists of users' })
@ApiOkResponse({})
@HttpCode(HttpStatus.OK)
async getAllUsers() {
return this.usersService.findAllUsers();
}
請找到 service.ts 文件代碼 -
async findAllUsers(): Promise<User[]> {
const users = await this.userModel.find().exec();
const usersArr = [];
await Promise.all(
users.map(async users => {
usersArr.push({ userId: users._id, firstName: users.firstName, lastName: users.lastName, email: users.email, status: users.status });
}),
);
return usersArr;
}
Thanks in advance!
創建給定的轉換攔截器
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; export interface Response<T> { statusCode: number; message: string; data: T; } @Injectable() export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> { intercept( context: ExecutionContext, next: CallHandler ): Observable<Response<T>> { return next.handle().pipe( map((data) => ({ statusCode: context.switchToHttp().getResponse().statusCode, reqId: context.switchToHttp().getRequest().reqId, message: data.message || '', data: data, })) ); } }
將上層攔截器添加到controller
@UseInterceptors(轉換攔截器)
導出 class DocumentController {}
最后返回controller的response。
每個響應都將通過此攔截器並創建一個 static 響應格式。
您可以根據需要修改攔截器。
I hope the following would help you
import {
Body,
Controller,
Get,
Param,
Res,
HttpStatus,
} from '@nestjs/common';
@Get('/users-listing')
// @UseGuards(AuthGuard('jwt'))
// @Roles('Super Admin')
@ApiOperation({ title: 'Lists of users' })
@ApiOkResponse({})
async getAllUsers(@Res() res) {
const users = this.usersService.findAllUsers();
return res.status(HttpStatus.OK).json({
status: 'success',
data: {
users,
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.