gpt4 book ai didi

javascript - 如何为每个 API 创建通用的 Nest JS API 响应格式?

转载 作者:行者123 更新时间:2023-12-05 00:33:09 25 4
gpt4 key购买 nike

我是 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(TransformInterceptor)
导出类 DocumentController {}
最后,从 Controller 返回响应。
每个响应都会通过这个拦截器并创建一个静态响应格式。
您可以根据需要修改拦截器。

关于javascript - 如何为每个 API 创建通用的 Nest JS API 响应格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66470409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com