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!