Reputation: 309
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": "[email protected]",
"status": "active"
},
{
"userId": "603f3b547508bbd77a3d6fb5",
"firstName": "Kunal",
"lastName": "Ghosh",
"email": "[email protected]",
"status": "active"
}
]
Need to set it as-
{
"statusCode": 200,
"message": "User Listing",
"data":[
{
"userId": "602a0f175bbd45688cd001f4",
"firstName": "Gagan",
"lastName": "Pandya",
"email": "[email protected]",
"status": "active"
},
{
"userId": "603f3b547508bbd77a3d6fb5",
"firstName": "Kunal",
"lastName": "Ghosh",
"email": "[email protected]",
"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!
Upvotes: 8
Views: 9890
Reputation: 449
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.
Upvotes: 7
Reputation: 11
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,
}
});
}
Upvotes: 0