In nestJs I needed to return data from multiple collections, so I've created a DTO to map these data, the DTO is like the following :
import { Injectable } from "@nestjs/common";
Injectable()
export class UserSummery{
static paymentHistory : Array<{ paymentType : object,
amountPaid : number,
paymentDate : Date
}> = [];
static requiredAmount: number;
And in some controller I wrote a function to get data from two different services:
@Post('getusersummery/:id')
async GetUserSummery(@Param('id') id: string) : Promise<UserSummery> {
let usrSummery = UserSummery;
const amount = await this.cachFlowService.GetUserRequiredAmount(id);
console.log(" amount" , amount);
let cond = {
family_member : id
};
let paymentHistory = await this.cachFlowService.getMemberPaymentHistory(cond);
usrSummery.requiredAmount = amount;
//console.log("payment history" , paymentHistory)
paymentHistory.forEach(function (payment) {
console.log("payment", payment);
console.log("payment.payment_type," , payment.payment_type);
usrSummery.paymentHistory.push({
paymentType : payment.payment_type["payment_type"],
amountPaid : payment.amount,
paymentDate : payment.createdAt
})
});
console.log("usersummmmmery", usrSummery);
return usrSummery;
}
the problem is i can see the data mapped well in console => console.log("usersummmmmery", usrSummery);
but the response from the request i make is class UserSummery { } Console Log shows
[{ paymentType: 'Donation', amountPaid: 45, paymentDate: 2022-04-25T04:49:04.247Z }, { paymentType: 'Loan', amountPaid: 1500, paymentDate: 2022-04-25T07:01:03.116Z } ], requiredAmount: 500 }
But for response,in the below screen that's what I get! what am I missing here?
CodePudding user response:
You are getting this because you are setting "usrSummery" to the CLASS UserSummery, not an instance of summary, and then you are setting static data (Which doesn't make much sense to be honest, you can just set static date by calling UserSummery.paymentHistory for example).
What I believe you want to do is have non-static data in the class and then let usrSummery = new UserSummery()
. If I am wrong and you intended to have it this way, you can get the results you're looking for by spreading the data into an actual instance of an object with return {...usrSummery}