when I use the property 'eager' for a relationship in typeORM, 'transformer' is triggered even though the value of the model being targeted for the relationship(name: Withdrawal) is 'null'.
What can I do to prevent this? The attached pictures are my current code. Thanks :)
I'm guessing this happens because of the JOIN operation that takes place because of the eager relationship.
Let's take the most simple find
operation below:
findAll() {
return this.lossAssessmentRepository.find();
}
Considering your entities, calling await findAll()
will generate a query similar to the following:
SELECT
"LossAssessment"."id" AS "LossAssessment_id",
"Withdrawal"."id" AS "Withdrawal_id",
"Withdrawal"."userId" AS "Withdrawal_userId",
"Withdrawal"."lossAssessmentId" AS "Withdrawal_lossAssessmentId",
"Withdrawal"."bankCode" AS "Withdrawal_bankCode",
"Withdrawal"."accountNumber" AS "Withdrawal_accountNumber"
FROM "LossAssessment"
LEFT JOIN "Withdrawal"
ON "LossAssessment"."id" = "Withdrawal"."lossAssessmentId";
A sample of raw results would be:
LossAssessment_id | Withdrawal_id | Withdrawal_userId | Withdrawal_lossAssessmentId | Withdrawal_bankCode | Withdrawal_accountNumber |
---|---|---|---|---|---|
lossAssessmentId1 | withdrawalId1 | userId1 | lossAssessmentId1 | bankCode1 | accountNumber1 |
lossAssessmentId2 | NULL | NULL | NULL | NULL | NULL |
Now imagine typeorm converting this raw response to the entity class instances you have defined.
Withdrawal
entity. So typeorm will first create Withdrawal
entity and put it inside the LossAssessment
entity.Withdrawal
entity, and then that should be put inside LossAssessment
entity. Here, I'm guessing typeorm does not care if all the values are NULL
. It first tries to create the entity instance for Withdrawal
which would call your transformer in the process.You can simply modify your transformer to accept null values like this to fix your problem:
transformer: {
from(value: string | null): string | undefined {
return value ?? decrypt(value) : undefined;
},
...
}