|
1 | 1 | import * as Faker from 'faker'; |
2 | | -import { Connection } from 'typeorm'; |
| 2 | +import { Connection } from 'typeorm/connection/Connection'; |
3 | 3 | import { EntityFactoryInterface } from './EntityFactoryInterface'; |
4 | 4 | import { BluePrint } from './BluePrint'; |
5 | | -import { getConnection } from './connection'; |
6 | 5 |
|
7 | 6 |
|
8 | 7 | export class EntityFactory<Entity> implements EntityFactoryInterface<Entity> { |
9 | 8 |
|
10 | | - private connection: Connection | undefined; |
11 | 9 | private identifier = 'id'; |
12 | 10 | private eachFn: (obj: any, faker: typeof Faker) => Promise<any>; |
13 | 11 |
|
14 | 12 | constructor( |
15 | 13 | private faker: typeof Faker, |
| 14 | + private connection: Connection, |
16 | 15 | private blueprint: BluePrint<Entity>, |
17 | 16 | private args: any[]) { } |
18 | 17 |
|
19 | | - public returning(identifier: string): EntityFactory<Entity> { |
20 | | - this.identifier = identifier; |
21 | | - return this; |
22 | | - } |
23 | | - |
24 | 18 | public each(iterator: (entity: Entity, faker: typeof Faker) => Promise<any>): EntityFactory<Entity> { |
25 | 19 | this.eachFn = iterator; |
26 | 20 | return this; |
27 | 21 | } |
28 | 22 |
|
29 | | - public async create(amount: number = 1): Promise<Entity | Entity[] | undefined> { |
30 | | - this.connection = await getConnection(); |
31 | | - if (this.connection) { |
32 | | - const results: Entity[] = []; |
33 | | - for (let i = 0; i < amount; i++) { |
34 | | - const entity = await this.build(); |
| 23 | + public async make(): Promise<Entity> { |
| 24 | + return await this.makeEntity(this.blueprint.create(this.faker, this.args)); |
| 25 | + } |
| 26 | + |
| 27 | + public async create(): Promise<Entity> { |
| 28 | + const entity = await this.build(); |
| 29 | + if (typeof this.eachFn === 'function') { |
| 30 | + await this.eachFn(entity, this.faker); |
| 31 | + } |
| 32 | + return entity; |
| 33 | + } |
| 34 | + |
| 35 | + public async createMany(amount: number): Promise<Entity[]> { |
| 36 | + const results: Entity[] = []; |
| 37 | + for (let i = 0; i < amount; i++) { |
| 38 | + const entity = await this.create(); |
| 39 | + if (entity) { |
35 | 40 | results.push(entity); |
36 | | - if (typeof this.eachFn === 'function') { |
37 | | - await this.eachFn(entity, this.faker); |
38 | | - } |
39 | | - } |
40 | | - await this.connection.close(); |
41 | | - if (amount === 1) { |
42 | | - return results[0]; |
43 | 41 | } |
44 | | - return results; |
45 | 42 | } |
46 | | - return; |
| 43 | + return results; |
47 | 44 | } |
48 | 45 |
|
49 | 46 | private async build(): Promise<any> { |
50 | 47 | if (this.connection) { |
51 | | - const entity = await this.makeEntity(this.blueprint.callback(this.faker, this.args)); |
| 48 | + const entity = await this.make(); |
52 | 49 | const em = this.connection.createEntityManager(); |
53 | 50 | try { |
54 | 51 | return await em.save(this.blueprint.EntityClass, entity); |
|
0 commit comments