Search code examples
node.jstypescriptnestjstypeormclass-transformer

NestJS > TypeORM Mapping complex entities to complex DTOs


Im using class-transformer > plainToClass(entity, DTO) to map entities to DTO's

I've also implemented the associated transform.interceptor pattern described here.

Then I use @Expose() on members of my DTO's. This works great but I have a limitation, I need to map member DTO's in my parent DTO and this isn't happening, see simple example below

@Exclude()
export class ParentDTO{

  @Expose()
  pMember2 : string;

  @Expose()
  pMember2 : ChildDto[];
}

@Exclude()
export class ChildDTO{

  @Expose()
  cMember2 : string;
}

export class ParentEntity{
  pMember1 : number;
  pMember2 : string;
  pMember3 : string;
  pMember4
 : Child[];
}

export class ChildEntity{
  cMember1 : number;
  cMember2 : string;
  cMember3 : string;
}

Now if I run plainToClass(parentEntityFromDB, ParentDTO) I was hoping to get the following

ParentDTO{
  pMember2 : string;
  pMember2 : ChildDto[];
}

However, what I am getting is

ParentDTO{
  pMember2 : string;
  pMember2 : Child[]; //Including all original members
}

Basically plainToClass(entity, DTO) is not automatically mapping members to match the given DTO type.

Is there a way to do this or is this a limitation of the method??

Thanks


Solution

  • You have to specify the nested type with @Type:

    @Exclude()
    export class ParentDTO{
    
      @Expose()
      pMember2 : string;
    
      @Expose()
      @Type(() => ChildDto)
      pMember2 : ChildDto[];
    }
    

    With the @Type decorator, class-transformer instantiates a class for the given property when plainToClass is called. Otherwise, the nested property will stay a plain javascript object and hence your @Exclude will not be used.