2
votes

I have this class:

import {Column, Entity, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
import {Company} from "./company.entity";
import {classToPlain, Expose, Transform, Type} from 'class-transformer';

@Entity()
export class Space {

  @PrimaryGeneratedColumn('uuid')
  id?: string;

  @ManyToOne(() => Company)
  @Expose()
  @Type(() => Company)
  @Transform(async value => {
    const res = await value;
    console.log(res);
    return res;
  })
  company!: Promise<Company>;

  @Column()
  name!: string;

}

and this for the Company:


@Entity()
export class Company {

  @PrimaryGeneratedColumn('uuid')
  id?: string;

  @Column()
  name!: string;

  @OneToMany(() => Space, space => space.company, {
    cascade: true
  })
  spaces!: Promise<Space[]>;

}

For some reason, the Company always comes back as an empty object within the space object like this:

[
    {
        "id": "266F2B95-69AE-EA11-96D2-28187800655A",
        "name": "Main",
        "desks": 2,
        "company": {}
    }
]

even though the console.log spits out

Company {
  id: '09A8FB3E-C5AB-EA11-96D2-28187800655A',
  name: 'Name' }

what am I doing wrong here?

1

1 Answers

1
votes

Class-transformer calls the transform functions synchronously. You have to use an eager relation:

  @ManyToOne(() => Company, { eager: true })
  company!: Promise<Company>;

or load the property afterwards like:

export class Space {
  ...
  loadedCompany: Company
  ...
}

...

  for (const space of spaces) {
     space.loadedCompany = await space.company
  }