Skip to content

Commit 3e3897e

Browse files
author
Fabricio Vergara
authored
Seed entity with lazy relations
given following model: ```typescript @entity(User.TABLE_NAME) export class User { public static readonly TABLE_NAME = 'user'; @PrimaryGeneratedColumn() public id: number; @column({ name: 'first_name', nullable: false, }) public firstName: string; @column({ name: 'last_name', nullable: false, }) public lastName: string; @column({ name: 'email', nullable: false, unique: true, }) public email: string; @column({ name: 'password', nullable: false, }) public password: string; @manytomany(type => Authority, authority => authority.users) @jointable({ name: 'user_authority' }) public authorities: Promise<Authority[]>; } ``` To create a new user entity you need to assign a promise to the entity, but to save you need to pass the authority object directly as mentioned here: typeorm/typeorm#1180 (comment) ```typescript /** * User factory */ factory.define(User, (faker: typeof Faker, args: any[]) => { const gender = faker.random.number(1); const firstName = faker.name.firstName(gender); const lastName = faker.name.lastName(gender); const email = faker.internet.email(firstName, lastName); const authority = args[0] as Authority; const user = new User(); user.firstName = firstName; user.lastName = lastName; user.email = email; user.password = env.admin.password; user.authorities = Promise.resolve([authority]); return user; }); ````
1 parent d8f99f0 commit 3e3897e

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

src/lib/seeds/EntityFactory.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ export class EntityFactory<Entity> implements EntityFactoryInterface<Entity> {
7171
private async makeEntity(entity: Entity): Promise<Entity> {
7272
for (const attribute in entity) {
7373
if (entity.hasOwnProperty(attribute)) {
74+
if (this.isPromiseLike(typeof entity[attribute])) {
75+
entity[attribute] = await entity[attribute];
76+
}
77+
7478
if (typeof entity[attribute] === 'object' && entity[attribute] instanceof EntityFactory) {
7579
const subEntityFactory = entity[attribute];
7680
const subEntity = await (subEntityFactory as any).build();
@@ -81,4 +85,7 @@ export class EntityFactory<Entity> implements EntityFactoryInterface<Entity> {
8185
return entity;
8286
}
8387

88+
private isPromiseLike(object: any): boolean {
89+
return object && typeof object.then === 'function';
90+
}
8491
}

0 commit comments

Comments
 (0)