Skip to content

Commit ee2bf09

Browse files
author
hirsch
committed
Merge branch 'release/1.0.0-beta'
2 parents d74449b + dee35a1 commit ee2bf09

7 files changed

+176
-176
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "typeorm-seeding",
3-
"version": "0.0.1",
3+
"version": "1.0.0-beta",
44
"description": "TypeORM seeding",
55
"bin": {
66
"seed": "./dist/cli.js"

src/cli.ts

+56-56
Original file line numberDiff line numberDiff line change
@@ -8,85 +8,85 @@ import { loadSeeds } from './importer';
88

99
// Cli helper
1010
commander
11-
.version('1.0.0')
12-
.description('Run database seeds of your project')
13-
.option('-L, --logging', 'enable sql query logging')
14-
.option('--factories <path>', 'add filepath for your factories')
15-
.option('--seeds <path>', 'add filepath for your seeds')
16-
.option('--run <seeds>', 'run specific seeds (file names without extension)', (val) => val.split(','))
17-
.option('--config <file>', 'path to your ormconfig.json file (must be a json)')
18-
.parse(process.argv);
11+
.version('1.0.0')
12+
.description('Run database seeds of your project')
13+
.option('-L, --logging', 'enable sql query logging')
14+
.option('--factories <path>', 'add filepath for your factories')
15+
.option('--seeds <path>', 'add filepath for your seeds')
16+
.option('--run <seeds>', 'run specific seeds (file names without extension)', (val) => val.split(','))
17+
.option('--config <file>', 'path to your ormconfig.json file (must be a json)')
18+
.parse(process.argv);
1919

2020
// Get cli parameter for a different factory path
2121
const factoryPath = (commander.factories)
22-
? commander.factories
23-
: 'src/database/';
22+
? commander.factories
23+
: 'src/database/';
2424

2525
// Get cli parameter for a different seeds path
2626
const seedsPath = (commander.seeds)
27-
? commander.seeds
28-
: 'src/database/seeds/';
27+
? commander.seeds
28+
: 'src/database/seeds/';
2929

3030
// Get a list of seeds
3131
const listOfSeeds = (commander.run)
32-
? commander.run.map(l => l.trim()).filter(l => l.length > 0)
33-
: [];
32+
? commander.run.map(l => l.trim()).filter(l => l.length > 0)
33+
: [];
3434

3535
// Search for seeds and factories
3636
const run = async () => {
37-
const log = console.log;
37+
const log = console.log;
3838

39-
let factoryFiles;
40-
let seedFiles;
41-
try {
42-
factoryFiles = await loadEntityFactories(factoryPath);
43-
seedFiles = await loadSeeds(seedsPath);
44-
} catch (error) {
45-
return handleError(error);
46-
}
39+
let factoryFiles;
40+
let seedFiles;
41+
try {
42+
factoryFiles = await loadEntityFactories(factoryPath);
43+
seedFiles = await loadSeeds(seedsPath);
44+
} catch (error) {
45+
return handleError(error);
46+
}
4747

48-
// Filter seeds
49-
if (listOfSeeds.length > 0) {
50-
seedFiles = seedFiles.filter(sf => listOfSeeds.indexOf(path.basename(sf).replace('.ts', '')) >= 0);
51-
}
48+
// Filter seeds
49+
if (listOfSeeds.length > 0) {
50+
seedFiles = seedFiles.filter(sf => listOfSeeds.indexOf(path.basename(sf).replace('.ts', '')) >= 0);
51+
}
5252

53-
// Status logging to print out the amount of factories and seeds.
54-
log(chalk.bold('seeds'));
55-
log('🔎 ', chalk.gray.underline(`found:`),
56-
chalk.blue.bold(`${factoryFiles.length} factories`, chalk.gray('&'), chalk.blue.bold(`${seedFiles.length} seeds`)));
53+
// Status logging to print out the amount of factories and seeds.
54+
log(chalk.bold('seeds'));
55+
log('🔎 ', chalk.gray.underline(`found:`),
56+
chalk.blue.bold(`${factoryFiles.length} factories`, chalk.gray('&'), chalk.blue.bold(`${seedFiles.length} seeds`)));
5757

58-
// Get database connection and pass it to the seeder
59-
let connection;
58+
// Get database connection and pass it to the seeder
59+
let connection;
60+
try {
61+
const connectionOptions = await getConnectionOptions();
62+
connection = await createConnection(connectionOptions);
63+
setConnection(connection);
64+
} catch (error) {
65+
return handleError(error);
66+
}
67+
68+
// Show seeds in the console
69+
for (const seedFile of seedFiles) {
6070
try {
61-
const connectionOptions = await getConnectionOptions();
62-
connection = await createConnection(connectionOptions);
63-
setConnection(connection);
71+
let className = seedFile.split('/')[seedFile.split('/').length - 1];
72+
className = className.replace('.ts', '').replace('.js', '');
73+
className = className.split('-')[className.split('-').length - 1];
74+
log('\n' + chalk.gray.underline(`executing seed: `), chalk.green.bold(`${className}`));
75+
const seedFileObject: any = require(seedFile);
76+
await runSeed(seedFileObject[className]);
6477
} catch (error) {
65-
return handleError(error);
66-
}
67-
68-
// Show seeds in the console
69-
for (const seedFile of seedFiles) {
70-
try {
71-
let className = seedFile.split('/')[seedFile.split('/').length - 1];
72-
className = className.replace('.ts', '').replace('.js', '');
73-
className = className.split('-')[className.split('-').length - 1];
74-
log('\n' + chalk.gray.underline(`executing seed: `), chalk.green.bold(`${className}`));
75-
const seedFileObject: any = require(seedFile);
76-
await runSeed(seedFileObject[className]);
77-
} catch (error) {
78-
console.error('Could not run seed ', error);
79-
process.exit(1);
80-
}
78+
console.error('Could not run seed ', error);
79+
process.exit(1);
8180
}
81+
}
8282

83-
log('\n👍 ', chalk.gray.underline(`finished seeding`));
84-
process.exit(0);
83+
log('\n👍 ', chalk.gray.underline(`finished seeding`));
84+
process.exit(0);
8585
};
8686

8787
const handleError = (error) => {
88-
console.error(error);
89-
process.exit(1);
88+
console.error(error);
89+
process.exit(1);
9090
};
9191

9292
run();

src/entity-factory.ts

+77-77
Original file line numberDiff line numberDiff line change
@@ -6,98 +6,98 @@ import { isPromiseLike } from './utils';
66

77
export class EntityFactory<Entity, Settings> {
88

9-
private mapFunction: (entity: Entity) => Promise<Entity>;
9+
private mapFunction: (entity: Entity) => Promise<Entity>;
1010

11-
constructor(
12-
public name: string,
13-
public entity: ObjectType<Entity>,
14-
private factory: FactoryFunction<Entity, Settings>,
15-
private settings?: Settings
16-
) { }
11+
constructor(
12+
public name: string,
13+
public entity: ObjectType<Entity>,
14+
private factory: FactoryFunction<Entity, Settings>,
15+
private settings?: Settings
16+
) { }
1717

18-
// -------------------------------------------------------------------------
19-
// Public API
20-
// -------------------------------------------------------------------------
18+
// -------------------------------------------------------------------------
19+
// Public API
20+
// -------------------------------------------------------------------------
2121

22-
/**
23-
* This function is used to alter the generated values of entity, before it
24-
* is persist into the database
25-
*/
26-
public map(mapFunction: (entity: Entity) => Promise<Entity>): EntityFactory<Entity, Settings> {
27-
this.mapFunction = mapFunction;
28-
return this;
29-
}
22+
/**
23+
* This function is used to alter the generated values of entity, before it
24+
* is persist into the database
25+
*/
26+
public map(mapFunction: (entity: Entity) => Promise<Entity>): EntityFactory<Entity, Settings> {
27+
this.mapFunction = mapFunction;
28+
return this;
29+
}
3030

31-
/**
32-
* Make a new entity, but does not persist it
33-
*/
34-
public async make(): Promise<Entity> {
35-
if (this.factory) {
36-
let entity = await this.resolveEntity(this.factory(Faker, this.settings));
37-
if (this.mapFunction) {
38-
entity = await this.mapFunction(entity);
39-
}
40-
return entity;
41-
}
42-
throw new Error('Could not found entity');
31+
/**
32+
* Make a new entity, but does not persist it
33+
*/
34+
public async make(): Promise<Entity> {
35+
if (this.factory) {
36+
let entity = await this.resolveEntity(this.factory(Faker, this.settings));
37+
if (this.mapFunction) {
38+
entity = await this.mapFunction(entity);
39+
}
40+
return entity;
4341
}
42+
throw new Error('Could not found entity');
43+
}
4444

45-
/**
46-
* Seed makes a new entity and does persist it
47-
*/
48-
public async seed(): Promise<Entity> {
49-
const connection: Connection = (global as any).seeder.connection;
50-
if (connection) {
51-
const em = connection.createEntityManager();
52-
try {
53-
const entity = await this.make();
54-
return await em.save<Entity>(entity);
55-
} catch (error) {
56-
throw new Error('Could not save entity');
57-
}
58-
} else {
59-
throw new Error('No db connection is given');
60-
}
45+
/**
46+
* Seed makes a new entity and does persist it
47+
*/
48+
public async seed(): Promise<Entity> {
49+
const connection: Connection = (global as any).seeder.connection;
50+
if (connection) {
51+
const em = connection.createEntityManager();
52+
try {
53+
const entity = await this.make();
54+
return await em.save<Entity>(entity);
55+
} catch (error) {
56+
throw new Error('Could not save entity');
57+
}
58+
} else {
59+
throw new Error('No db connection is given');
6160
}
61+
}
6262

63-
public async makeMany(amount: number): Promise<Entity[]> {
64-
const list = [];
65-
for (let index = 0; index < amount; index++) {
66-
list[index] = await this.make();
67-
}
68-
return list;
63+
public async makeMany(amount: number): Promise<Entity[]> {
64+
const list = [];
65+
for (let index = 0; index < amount; index++) {
66+
list[index] = await this.make();
6967
}
68+
return list;
69+
}
7070

71-
public async seedMany(amount: number): Promise<Entity[]> {
72-
const list = [];
73-
for (let index = 0; index < amount; index++) {
74-
list[index] = await this.seed();
75-
}
76-
return list;
71+
public async seedMany(amount: number): Promise<Entity[]> {
72+
const list = [];
73+
for (let index = 0; index < amount; index++) {
74+
list[index] = await this.seed();
7775
}
76+
return list;
77+
}
7878

79-
// -------------------------------------------------------------------------
80-
// Prrivat Helpers
81-
// -------------------------------------------------------------------------
79+
// -------------------------------------------------------------------------
80+
// Prrivat Helpers
81+
// -------------------------------------------------------------------------
8282

83-
private async resolveEntity(entity: Entity): Promise<Entity> {
84-
for (const attribute in entity) {
85-
if (entity.hasOwnProperty(attribute)) {
86-
if (isPromiseLike(entity[attribute])) {
87-
entity[attribute] = await entity[attribute];
88-
}
83+
private async resolveEntity(entity: Entity): Promise<Entity> {
84+
for (const attribute in entity) {
85+
if (entity.hasOwnProperty(attribute)) {
86+
if (isPromiseLike(entity[attribute])) {
87+
entity[attribute] = await entity[attribute];
88+
}
8989

90-
if (typeof entity[attribute] === 'object') {
91-
const subEntityFactory = entity[attribute];
92-
try {
93-
entity[attribute] = await (subEntityFactory as any).make();
94-
} catch (e) {
95-
throw new Error(`Could not make ${(subEntityFactory as any).name}`);
96-
}
97-
}
98-
}
90+
if (typeof entity[attribute] === 'object' && !(entity[attribute] instanceof Date)) {
91+
const subEntityFactory = entity[attribute];
92+
try {
93+
entity[attribute] = await (subEntityFactory as any).make();
94+
} catch (e) {
95+
throw new Error(`Could not make ${(subEntityFactory as any).name}`);
96+
}
9997
}
100-
return entity;
98+
}
10199
}
100+
return entity;
101+
}
102102

103103
}

src/importer.ts

+17-17
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@ import * as path from 'path';
88
const importFactories = (files: string[]) => files.forEach(require);
99

1010
const loadFiles =
11-
(filePattern: string) =>
12-
(pathToFolder: string) =>
13-
(successFn: (files: string[]) => void) =>
14-
(failedFn: (error: any) => void) => {
15-
glob(path.join(process.cwd(), pathToFolder, filePattern), (error: any, files: string[]) => error
16-
? failedFn(error)
17-
: successFn(files));
18-
};
11+
(filePattern: string) =>
12+
(pathToFolder: string) =>
13+
(successFn: (files: string[]) => void) =>
14+
(failedFn: (error: any) => void) => {
15+
glob(path.join(process.cwd(), pathToFolder, filePattern), (error: any, files: string[]) => error
16+
? failedFn(error)
17+
: successFn(files));
18+
};
1919

2020
const loadFactoryFiles = loadFiles('**/*Factory{.js,.ts}');
2121

@@ -24,16 +24,16 @@ const loadFactoryFiles = loadFiles('**/*Factory{.js,.ts}');
2424
// -------------------------------------------------------------------------
2525

2626
export const loadEntityFactories = (pathToFolder: string): Promise<string[]> => {
27-
return new Promise((resolve, reject) => {
28-
loadFactoryFiles(pathToFolder)(files => {
29-
importFactories(files);
30-
resolve(files);
31-
})(reject);
32-
});
27+
return new Promise((resolve, reject) => {
28+
loadFactoryFiles(pathToFolder)(files => {
29+
importFactories(files);
30+
resolve(files);
31+
})(reject);
32+
});
3333
};
3434

3535
export const loadSeeds = (pathToFolder: string): Promise<string[]> => {
36-
return new Promise((resolve, reject) => {
37-
loadFiles('**/*{.js,.ts}')(pathToFolder)(resolve)(reject);
38-
});
36+
return new Promise((resolve, reject) => {
37+
loadFiles('**/*{.js,.ts}')(pathToFolder)(resolve)(reject);
38+
});
3939
};

0 commit comments

Comments
 (0)