Skip to content

Commit 45344c3

Browse files
committed
Refactor app.module.ts to enable MigrationsModule
1 parent ad77d1f commit 45344c3

File tree

2 files changed

+55
-22
lines changed

2 files changed

+55
-22
lines changed

src/app.module.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ import { MigrationsModule } from './migrations/migrations.module';
9494
CoreModule.register(),
9595
ManagementModule.register(),
9696
SettingsModule.register(),
97-
// MigrationsModule.register(),
97+
MigrationsModule.register(),
9898
],
9999
controllers: [AppController],
100100
providers: [

src/migrations/migrations.service.ts

Lines changed: 54 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,55 @@ import chalk from 'chalk'
44
import { ModuleRef } from '@nestjs/core'
55
import { startLoader, stopLoader } from './migration-loader.function'
66
import { readFile, writeFile } from 'fs/promises'
7+
import { posix } from 'path'
78

89
@Injectable()
910
export class MigrationsService implements OnModuleInit {
1011
private readonly logger = new Logger(`${chalk.bold.red(MigrationsService.name)}\x1b[33m`)
1112

1213
protected migrations = new Map<string, any>()
1314

14-
public constructor(private readonly moduleRef: ModuleRef) { }
15+
protected lockLocation = posix.join(process.cwd(), 'migrations.lock')
16+
17+
public constructor(private readonly moduleRef: ModuleRef) {
18+
}
1519

1620
public async onModuleInit() {
17-
await this._checkMigrationLockFile()
18-
this.logger.log(chalk.yellow('Checking migrations files...'));
19-
await this._loadMigrationsFiles();
21+
this.logger.debug(chalk.yellow('Migrations service initialized.'));
22+
this.logger.debug(chalk.yellow('Lock file location: ' + this.lockLocation));
23+
const currentTimestamp = await this._checkMigrationLockFile()
24+
this.logger.debug(chalk.yellow('Checking migrations files...'));
25+
await this._loadMigrationsFiles(currentTimestamp);
2026

2127
const loader = startLoader('Migration en cours...');
2228
await this._executeMigrations();
2329
stopLoader(loader);
2430
}
2531

2632
private async _checkMigrationLockFile() {
27-
let migrationTimestamp = 0
33+
let currentTimestamp = 0
2834

2935
try {
30-
const migration = await readFile('./migrations.lock', 'utf-8')
31-
console.log('migration', migration)
36+
const migration = await readFile(this.lockLocation, 'utf-8')
37+
currentTimestamp = parseInt(migration, 10)
38+
this.logger.log(chalk.blue(`Migration lock state is <${currentTimestamp}> !`));
3239
} catch (error) {
3340
this.logger.warn(chalk.red('No migration lock file found.'))
3441
}
3542

36-
if (migrationTimestamp === 0) {
43+
if (currentTimestamp === 0) {
3744
try {
38-
await writeFile('./migrations.lock', migrationTimestamp.toString())
45+
await writeFile(this.lockLocation, currentTimestamp.toString())
3946
this.logger.log(chalk.green('Migration lock file created.'))
4047
} catch (error) {
4148
this.logger.error(chalk.red('Error while creating migration lock file !'))
4249
}
4350
}
51+
52+
return currentTimestamp
4453
}
4554

46-
private async _loadMigrationsFiles() {
47-
const currentTimestamp = 1729092659
48-
// const currentTimestamp = Date.now()
55+
private async _loadMigrationsFiles(currentTimestamp = 0) {
4956
let files = await glob(`./jobs/*.js`, {
5057
cwd: __dirname,
5158
root: __dirname,
@@ -59,7 +66,7 @@ export class MigrationsService implements OnModuleInit {
5966
return;
6067
}
6168

62-
if (parseInt(timestampMatch) < currentTimestamp) {
69+
if (parseInt(timestampMatch) <= currentTimestamp) {
6370
this.logger.debug(chalk.yellow(`Migration ${chalk.bold('<' + file.replace(/.js$/, '') + '>')} are already executed !`));
6471
return false;
6572
}
@@ -76,22 +83,24 @@ export class MigrationsService implements OnModuleInit {
7683

7784
for (const file of files) {
7885
const migration = await import(`${__dirname}/${file}`);
79-
const [timestampMatch] = file.match(/\d{10,}/) || []
80-
81-
console.log('file', timestampMatch)
8286

8387
if (!migration.default) {
8488
this.logger.log(chalk.yellow(`Migration ${chalk.bold('<' + file + '>')} does not have a default export !`));
8589
return;
8690
}
8791

88-
this.migrations.set(timestampMatch, migration)
92+
this.migrations.set(file, migration)
8993
}
9094
}
9195

9296
private async _executeMigrations() {
97+
if (this.migrations.size === 0) {
98+
this.logger.log(chalk.green('No migrations to execute.'));
99+
return;
100+
}
101+
93102
for (const key of this.migrations.keys()) {
94-
this.logger.log(chalk.yellow(`Running migration ${chalk.bold('<' + key + '>')}...`));
103+
const [migrationTimestamp] = key.match(/\d{10,}/) || []
95104

96105
const migration = this.migrations.get(key);
97106
const instance = await this.moduleRef.create(migration.default);
@@ -101,10 +110,34 @@ export class MigrationsService implements OnModuleInit {
101110
break;
102111
}
103112

104-
this.logger.log(chalk.yellow(`Running migration ${chalk.bold('<' + key + '>')}...`));
105-
await instance.up();
113+
try {
114+
this.logger.log(chalk.yellow(`Running migration ${chalk.bold('<' + key + '>')}...`));
115+
await instance.up();
116+
} catch (e) {
117+
this.logger.error(chalk.red(`Error while running migration ${chalk.bold('<' + key + '>')} !`));
118+
this.logger.error(e);
119+
break;
120+
}
121+
122+
try {
123+
await writeFile('./migrations.lock', migrationTimestamp);
124+
this.logger.log(chalk.blue(`Migration ${chalk.bold('<' + key + '>')} done.`));
125+
} catch (e) {
126+
this.logger.error(chalk.red(`Error while updating migration lock file !`));
127+
this.logger.error(e);
128+
break
129+
}
130+
}
131+
132+
this.logger.log(chalk.blue('All migrations done.'));
133+
}
134+
135+
private async _validateMigration(migration: any) {
136+
if (!migration.default) {
137+
this.logger.log(chalk.yellow(`Migration ${chalk.bold('<' + migration + '>')} does not have a default export !`));
138+
return false;
106139
}
107140

108-
this.logger.log(chalk.green('All migrations done.'));
141+
return true;
109142
}
110143
}

0 commit comments

Comments
 (0)