简体   繁体   中英

How to create Nest JS API response format common for each API?

I am new to nestjs and was stuck with making a common response body for all the APIs. Currently, I am making use of the map for getting the response from the collection but not have an idea how to format the response in the below-mentioned way.

I am currently getting response body like below -

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

Need to set it as-

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

Below is my controller code -

  @Get('/users-listing')    
  // @UseGuards(AuthGuard('jwt'))    
 // @Roles('Super Admin')    
  @ApiOperation({ title: 'Lists of users' })    
  @ApiOkResponse({})    
  @HttpCode(HttpStatus.OK)    
  async getAllUsers() {    
    return this.usersService.findAllUsers();    
  }    
           

And please find service.ts file code -

   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!   

Create a given transform interceptor

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

Add the upper interceptor to the controller

@UseInterceptors(TransformInterceptor)

export class DocumentController {}

Finally, return the response from the controller.

Every response will pass through this interceptor and create a static response format.

You can modify the interceptor according to your requirement.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM