【问题标题】:How to create Nest JS API response format common for each API?如何为每个 API 创建通用的 Nest JS API 响应格式?
【发布时间】:2021-06-02 19:51:34
【问题描述】:

我是 nestjs 的新手,一直坚持为所有 API 制作一个通用的响应体。目前,我正在使用地图从集合中获取响应,但不知道如何以下面提到的方式格式化响应。

我目前收到如下响应正文 -

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"    
  }     
]    
}    

以下是我的控制器代码 -

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

【问题讨论】:

  • 这能回答你的问题吗? How to format response before sending in Nest.js?
  • @JayMcDoniel 感谢您的回复。实际上我想要实现的是我需要一个通用的响应体,说它是一个处理响应的通用函数,我也可以将它用于其他 API。
  • 您可以将元数据应用到每个路由,并使用context.getHandler() 获取当前方法,以便您可以获取每个方法的元数据
  • 好的,当然 JayMcDoniel 让我试试这个。谢谢!

标签: javascript node.js nestjs


【解决方案1】:

希望以下内容对你有所帮助

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,
        }
    });
}

【讨论】:

    猜你喜欢
    • 2019-05-03
    • 2019-09-06
    • 1970-01-01
    • 2018-02-01
    • 2021-08-07
    • 2021-11-21
    • 1970-01-01
    • 2020-11-08
    • 2020-07-30
    相关资源
    最近更新 更多