Search code examples
nestjstypeorm

Which code is correct when using TypeOrm Lazy Type?


The official TypeOrm document says to use Promise when using Lazy Type. But I didn't use that method because I had the Lazy option. What is the difference between the two methods?

@Entity('COMPANY')
export class Company extends TimeStamped {
    @PrimaryGeneratedColumn('increment')
    companyId: number;

    @Column({ type: 'varchar' })
    companyName: string;

    @OneToMany(() => Employee, (employee) => employee.company, {
        onDelete: 'CASCADE',
        lazy: true
    })
    employee: Employee[];
}
@Entity('COMPANY')
export class Company extends TimeStamped {
    @PrimaryGeneratedColumn('increment')
    companyId: number;

    @Column({ type: 'varchar' })
    companyName: string;

    @OneToMany(() => Employee, (employee) => employee.company, {
        onDelete: 'CASCADE'
    })
    employee: Promise<Employee[]>;
}

Solution

  • If you check Typeorm relation options code:

    export interface RelationOptions {
        ...
    
        /**
         * Set this relation to be lazy. Note: lazy relations are promises.
         * When you call them they return a promise which resolves relation 
         * result then. If your property's type is Promise then this relation
         * is set to lazy automatically.
         */
        lazy?: boolean;
    
        ...
    }
    

    In your first example, when you want the value of employee you will have to write something like:

    const employees = await company.employee;
    

    But if a developer checks the code later, he might be confused as why there is an await on a property of a class that is not a promise.

    In your seconds example, you will write the same code as above. But now, any developer will know that the property is a promise therefore they have to await (This will also help the ESLint).

    So ideally, you should use your second example or the following one which I believe is more intuitive to the developer:

    @OneToMany(() => Employee, (employee) => employee.company, {
      onDelete: 'CASCADE',
      lazy: true
    })
    employee: Promise<Employee[]>;