typeormnode.js-typeormnestjs-typeorm

In typeORM, 'transformer' is triggered even though the value of the model being targeted for the relationship is 'null'


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 :)

enter image description here

enter image description here

enter image description here


Solution

  • 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.

    1. The first row will have no issue because it has non-null values for Withdrawal entity. So typeorm will first create Withdrawal entity and put it inside the LossAssessment entity.
    2. The second raw needs to be converted to 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;
      },
      ...
    }