Search code examples
serializationnestjstypeorm

Nest JS - Serialization not work with nested object


I want to append a new field called logo_img_url after data manipulation. It works with the object but the nested array object seems not to work. Any recommendations or solution

import { Expose } from 'class-transformer';
import {} from 'class-validator';
import { Entity, Column } from 'typeorm';

import { BaseEntity } from '@common/base/entity.base';
import { getAdminImageUrl } from '@common/util/vault-file.util';

@Entity()
export class Agency extends BaseEntity {

  @Expose()
  @Column({
    type: 'varchar',
    length: '255',
    nullable: true,
  })
  public logo_key!: string;

  @Expose({ name: 'logoImgUrl' })
  logo_img_url = this.logoImgUrl;

  @Expose()
  get logoImgUrl(): any {
    return "http://localhost:30001/". this.logo_key;
  }
}

Actaul response:

{
  "data": [
    {
      "logo_img_url": "",
      "id": 22,
      "logo_url": "9597e74d-aaea-4502-b5cd-b2867504fd80",
    },
    {
      "logo_img_url": "",
      "id": 21,
      "logo_url": "0a655497-1318-4276-a21f-cfdc259241a2",
    },
  ],
  "meta": {
    "status_code": 200,
    "pagination": {
      "totalPages": 1,
      "currentPage": 1,
      "nextPage": null,
      "paginationToken": null,
      "previousPage": null,
      "totalItems": 9,
      "itemsPerPage": 10
    }
  }
}

Expected result:

{
  "data": [
    {
      "logo_img_url": "http://localhost:3000/9597e74d-aaea-4502-b5cd-b2867504fd80",
      "id": 22,
      "logo_url": "9597e74d-aaea-4502-b5cd-b2867504fd80",
    },
    {
      "logo_img_url": "http://localhost:3000/0a655497-1318-4276-a21f-cfdc259241a2",
      "id": 21,
      "logo_url": "0a655497-1318-4276-a21f-cfdc259241a2",
    },
  ],
  "meta": {
    "status_code": 200,
    "pagination": {
      "totalPages": 1,
      "currentPage": 1,
      "nextPage": null,
      "paginationToken": null,
      "previousPage": null,
      "totalItems": 9,
      "itemsPerPage": 10
    }
  }
}

Solution

  • You can use @AfterLoad decorator from typeorm. Its calls the decorated method once the entity is loaded and then one can perform the required manipulations.

    logo_img_url:string
    
    @AfterLoad()
    async transform(){
    this.logo_img_url=`http://localhost:30001/${this.logo_key}`
    }