-
Notifications
You must be signed in to change notification settings - Fork 25
/
mongo.command.ts
56 lines (53 loc) 路 1.86 KB
/
mongo.command.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { ConsoleService } from '@nestify/console';
import { SeederService } from '@nestify/mongo-seeder';
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
@Injectable()
export class MongoCommand {
constructor(
private readonly cli: ConsoleService,
private readonly seedService: SeederService,
@InjectConnection()
private readonly connection: Connection
) {
this.cli
.getCli()
.version('0.1.0')
.command('seed')
.arguments('[models...]')
.option('-d, --drop', 'Drop database')
.description('Run all database seed files.')
.action(this.seed.bind(this));
}
async seed(models: string[], cmd: any) {
const sp = ConsoleService.createSpinner();
try {
if (!!cmd.drop) {
sp.start('Start dropping database...');
this.connection.dropDatabase();
sp.info('Database dropped');
}
sp.start('Start scanning database seed files...');
if (models.length > 0) {
for (const model of models) {
sp.info(`Generated seed for ${model}`);
const seeder = this.seedService.Seeders.find((m) => m.modelName === model);
await seeder.seed();
}
} else {
for (const seeder of this.seedService.Seeders) {
sp.info(`Generated seed for ${seeder.modelName}`);
await seeder.seed();
}
}
sp.succeed('Run successfully');
} catch (err) {
sp.fail('Failed to run');
console.error(err);
} finally {
sp.stop();
this.cli.exit();
}
}
}