Skip to content

Commit 43847b0

Browse files
author
hirsch88
committed
refactor the new seed
1 parent 2a6f775 commit 43847b0

File tree

9 files changed

+93
-96
lines changed

9 files changed

+93
-96
lines changed

src/database/seeds/CreatePets.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
import { Connection } from 'typeorm';
22

3-
import { Factory, Seed } from '../../lib/seed/types';
3+
import { Pet } from '../../../src/api/models/Pet';
4+
import { User } from '../../../src/api/models/User';
5+
import { Factory, Seed, times } from '../../lib/seed';
46

5-
// import { Pet } from '../../../src/api/models/Pet';
6-
// import { User } from '../../../src/api/models/User';
77
export class CreatePets implements Seed {
88

99
public async seed(factory: Factory, connection: Connection): Promise<any> {
1010
console.log('CreatePets');
1111

1212
// const connection = await factory.getConnection();
13-
// const em = connection.createEntityManager();
13+
const em = connection.createEntityManager();
1414

15-
// await times(10, async (n) => {
16-
// const pet = await factory.get(Pet).create();
17-
// const user = await factory.get(User).make();
18-
// user.pets = [pet];
19-
// await em.save(user);
20-
// });
15+
await times(10, async (n) => {
16+
const pet = await factory<Pet, undefined>(Pet as any)().seed();
17+
const user = await factory<User, undefined>(User as any)().make();
18+
user.pets = [pet];
19+
await em.save(user);
20+
});
2121
}
2222

2323
}

src/database/seeds/CreateUsers.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
import { Connection } from 'typeorm/connection/Connection';
22

3+
import { User } from '../../../src/api/models/User';
34
import { Factory, Seed } from '../../lib/seed/types';
45

5-
// import { User } from '../../../src/api/models/User';
66
export class CreateUsers implements Seed {
77

88
public async seed(factory: Factory, connection: Connection): Promise<any> {
99
console.log('CreateUsers');
1010

11-
// await factory
12-
// .get(User)
13-
// .createMany(10);
11+
await factory(User)()
12+
.seedMany(10);
1413
}
1514

1615
}

src/lib/seed/EntityFactory.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ import { Connection } from 'typeorm/connection/Connection';
44
import { FactoryFunction } from './types';
55
import { isPromiseLike } from './utils';
66

7+
/**
8+
* EntityFactory ...
9+
*/
710
export class EntityFactory<Entity, Settings> {
811

912
private mapFunction: (entity: Entity) => Promise<Entity>;
@@ -19,11 +22,18 @@ export class EntityFactory<Entity, Settings> {
1922
// Public API
2023
// -------------------------------------------------------------------------
2124

25+
/**
26+
* This fucntion is used to alter the generated values of entity, before it
27+
* is persist into the database
28+
*/
2229
public map(mapFunction: (entity: Entity) => Promise<Entity>): EntityFactory<Entity, Settings> {
2330
this.mapFunction = mapFunction;
2431
return this;
2532
}
2633

34+
/**
35+
* Make generate a new entity, but does not persist it
36+
*/
2737
public async make(): Promise<Entity> {
2838
if (this.factory) {
2939
let entity = await this.resolveEntity(this.factory(Faker, this.settings));
@@ -35,6 +45,9 @@ export class EntityFactory<Entity, Settings> {
3545
throw new Error('Could not found entity');
3646
}
3747

48+
/**
49+
* Seed persist and generates a given entity
50+
*/
3851
public async seed(): Promise<Entity> {
3952
const connection: Connection = (global as any).seeder.connection;
4053
if (connection) {

src/lib/seed/cli.ts

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@ import * as path from 'path';
55
import { loadEntityFactories } from './';
66
import { getConnection } from './connection';
77
import { loadSeeds } from './importer';
8-
import { runSeeder, setConnection } from './index';
9-
import { SeedConstructor } from './types';
8+
import { runSeed, setConnection } from './index';
109

1110
// Cli helper
1211
commander
13-
.version('0.0.0')
12+
.version('1.0.0')
1413
.description('Run database seeds of your project')
1514
.option('-L, --logging', 'enable sql query logging')
1615
.option('--factories <path>', 'add filepath for your factories')
@@ -91,8 +90,4 @@ const handleError = (error) => {
9190
process.exit(1);
9291
};
9392

94-
const runSeed = async (seedClass: SeedConstructor): Promise<void> => {
95-
await runSeeder(seedClass);
96-
};
97-
9893
run();

src/lib/seed/importer.ts

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,9 @@ const loadFiles =
1212
(pathToFolder: string) =>
1313
(successFn: (files: string[]) => void) =>
1414
(failedFn: (error: any) => void) => {
15-
glob(path.join(process.cwd(), pathToFolder, filePattern), (error: any, files: string[]) => {
16-
if (error) {
17-
return failedFn(error);
18-
}
19-
successFn(files);
20-
});
21-
// error
22-
// ? failedFn(error)
23-
// : successFn(files));
15+
glob(path.join(process.cwd(), pathToFolder, filePattern), (error: any, files: string[]) => error
16+
? failedFn(error)
17+
: successFn(files));
2418
};
2519

2620
const loadFactoryFiles = loadFiles('**/*Factory{.js,.ts}');
@@ -40,9 +34,6 @@ export const loadEntityFactories = (pathToFolder: string): Promise<string[]> =>
4034

4135
export const loadSeeds = (pathToFolder: string): Promise<string[]> => {
4236
return new Promise((resolve, reject) => {
43-
loadFiles('**/*{.js,.ts}')(pathToFolder)(files => {
44-
// TODO: load seeds
45-
resolve(files);
46-
})(reject);
37+
loadFiles('**/*{.js,.ts}')(pathToFolder)(resolve)(reject);
4738
});
4839
};

src/lib/seed/index.ts

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,18 @@ import 'reflect-metadata';
22
import { Connection, ObjectType } from 'typeorm';
33

44
import { EntityFactory } from './EntityFactory';
5-
import { EntityFactoryDefinition, FactoryFunction, SeedConstructor } from './types';
5+
import {
6+
EntityConstructor, EntityFactoryDefinition, FactoryFunction, SeedConstructor
7+
} from './types';
68
import { getNameOfClass } from './utils';
79

810
// -------------------------------------------------------------------------
911
// Handy Exports
1012
// -------------------------------------------------------------------------
1113

1214
export * from './importer';
15+
export { Factory, Seed } from './types';
16+
export { times } from './utils';
1317

1418
// -------------------------------------------------------------------------
1519
// Types & Variables
@@ -20,23 +24,32 @@ export * from './importer';
2024
entityFactories: new Map<string, EntityFactoryDefinition<any, any>>(),
2125
};
2226

23-
// -------------------------------------------------------------------------
24-
// Util functions
25-
// -------------------------------------------------------------------------
26-
2727
// -------------------------------------------------------------------------
2828
// Facade functions
2929
// -------------------------------------------------------------------------
3030

31+
/**
32+
* Adds the typorm connection to the seed options
33+
*/
3134
export const setConnection = (connection: Connection) => (global as any).seeder.connection = connection;
3235

36+
/**
37+
* Returns the typorm connection from our seed options
38+
*/
3339
export const getConnection = () => (global as any).seeder.connection;
3440

41+
/**
42+
* Defines a new entity factory
43+
*/
3544
export const define = <Entity, Settings>(entity: ObjectType<Entity>, factoryFn: FactoryFunction<Entity, Settings>) => {
3645
(global as any).seeder.entityFactories.set(getNameOfClass(entity), { entity, factory: factoryFn });
3746
};
3847

39-
export const factory = <Entity, Settings>(entity: any) => (settings?: Settings) => {
48+
49+
/**
50+
* Gets a defined entity factory and pass the settigns along to the entity factory function
51+
*/
52+
export const factory = <Entity, Settings>(entity: EntityConstructor<Entity>) => (settings?: Settings) => {
4053
const name = getNameOfClass(entity);
4154
const entityFactoryObject = (global as any).seeder.entityFactories.get(name);
4255
return new EntityFactory<Entity, Settings>(
@@ -47,22 +60,10 @@ export const factory = <Entity, Settings>(entity: any) => (settings?: Settings)
4760
);
4861
};
4962

50-
export const seed = async <Entity, Settings>(entityFactory: EntityFactory<Entity, Settings>): Promise<Entity> => {
51-
const connection: Connection = (global as any).seeder.connection;
52-
if (connection) {
53-
const em = connection.createEntityManager();
54-
try {
55-
const entity = await entityFactory.make();
56-
return await em.save<Entity>(entityFactory.entity, entity);
57-
} catch (error) {
58-
throw new Error('Could not save entity');
59-
}
60-
} else {
61-
throw new Error('No db connection is given');
62-
}
63-
};
64-
65-
export const runSeeder = async <T>(seederConstructor: SeedConstructor): Promise<T> => {
63+
/**
64+
* Runs a seed class
65+
*/
66+
export const runSeed = async <T>(seederConstructor: SeedConstructor): Promise<T> => {
6667
const seeder = new seederConstructor();
6768
return seeder.seed(factory, getConnection());
6869
};

src/lib/seed/make.ts

Lines changed: 0 additions & 31 deletions
This file was deleted.

src/lib/seed/types.ts

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,34 @@ import { Connection, ObjectType } from 'typeorm';
33

44
import { EntityFactory } from './EntityFactory';
55

6+
/**
7+
* FactoryFunction is the fucntion, which generate a new filled entity
8+
*/
69
export type FactoryFunction<Entity, Settings> = (faker: typeof Faker, settings?: Settings) => Entity;
710

11+
/**
12+
* Factory gets the EntityFactory to the given Entity and pass the settings along
13+
*/
814
export type Factory = <Entity, Settings>(entity: Entity) => (settings?: Settings) => EntityFactory<Entity, Settings>;
915

10-
export interface EntityFactoryDefinition<Entity, Settings> {
11-
entity: ObjectType<Entity>;
12-
factory: FactoryFunction<Entity, Settings>;
13-
}
14-
16+
/**
17+
* Seed are the class to create some data. Those seed are run by the cli.
18+
*/
1519
export interface Seed {
1620
seed(factory: Factory, connection: Connection): Promise<any>;
1721
}
1822

23+
/**
24+
* Constructor of the seed class
25+
*/
1926
export interface SeedConstructor {
2027
new(): Seed;
2128
}
29+
30+
/**
31+
* Value of our EntityFactory state
32+
*/
33+
export interface EntityFactoryDefinition<Entity, Settings> {
34+
entity: ObjectType<Entity>;
35+
factory: FactoryFunction<Entity, Settings>;
36+
}

src/lib/seed/utils.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,21 @@
1-
// -------------------------------------------------------------------------
2-
// Util functions
3-
// -------------------------------------------------------------------------
4-
1+
/**
2+
* Returns the name of a class
3+
*/
54
export const getNameOfClass = (c: any): string => new c().constructor.name;
65

6+
/**
7+
* Checks if the given argument is a promise
8+
*/
79
export const isPromiseLike = (o: any): boolean => !!o && (typeof o === 'object' || typeof o === 'function') && typeof o.then === 'function';
10+
11+
/**
12+
* Times repeats a function n times
13+
*/
14+
export const times = async <TResult>(n: number, iteratee: (index: number) => Promise<TResult>): Promise<TResult[]> => {
15+
const rs = [] as TResult[];
16+
for (let i = 0; i < n; i++) {
17+
const r = await iteratee(i);
18+
rs.push(r);
19+
}
20+
return rs;
21+
};

0 commit comments

Comments
 (0)