Skip to content

Commit c87c37c

Browse files
committed
Refactor .gitignore and app.module.ts, and remove unnecessary migration files
1 parent 0a638a7 commit c87c37c

File tree

9 files changed

+130
-64
lines changed

9 files changed

+130
-64
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,5 @@ documentation/*
4343
app/.idea/modules.xml
4444
app/.idea/app.iml
4545
app/.idea/inspectionProfiles/Project_Default.xml
46+
47+
migrations.lock

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: [
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { Logger } from "@nestjs/common"
2+
import { InjectConnection } from "@nestjs/mongoose"
3+
import { Connection } from "mongoose"
4+
5+
export default class EmployeeNumber1729092595 {
6+
public constructor(@InjectConnection() private connection: Connection) {
7+
8+
}
9+
10+
public async up(): Promise<void> {
11+
Logger.log('EmployeeNumber1729092595 up')
12+
13+
Logger.log('this.connection.readyState', this.connection.readyState)
14+
15+
return new Promise((resolve) => {
16+
const interval = setInterval(() => {
17+
Logger.log('EmployeeNumber1729092595 up in progress')
18+
}, 1_000)
19+
20+
setTimeout(() => {
21+
clearInterval(interval)
22+
Logger.log('EmployeeNumber1729092595 up done')
23+
1729092595
24+
resolve()
25+
}, 5_000)
26+
})
27+
}
28+
29+
public async down(): Promise<void> {
30+
Logger.log('EmployeeNumber1729092595 down')
31+
}
32+
}

src/migrations/jobs/1316027432511-employee-number.ts renamed to src/migrations/jobs/1729092660-employee-number.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,31 @@ import { Logger } from "@nestjs/common"
22
import { InjectConnection } from "@nestjs/mongoose"
33
import { Connection } from "mongoose"
44

5-
export default class EmployeeNumber1616027432511 {
5+
export default class EmployeeNumber1729092660 {
66
public constructor(@InjectConnection() private connection: Connection) {
77

88
}
99

1010
public async up(): Promise<void> {
11-
Logger.log('EmployeeNumber1616027432511 up')
11+
Logger.log('EmployeeNumber1729092660 up')
1212

1313
Logger.log('this.connection.readyState', this.connection.readyState)
1414

1515
return new Promise((resolve) => {
1616
const interval = setInterval(() => {
17-
Logger.log('EmployeeNumber1616027432511 up in progress')
17+
Logger.log('EmployeeNumber1729092660 up in progress')
1818
}, 1_000)
1919

2020
setTimeout(() => {
2121
clearInterval(interval)
22-
Logger.log('EmployeeNumber1616027432511 up done')
22+
Logger.log('EmployeeNumber1729092660 up done')
2323

2424
resolve()
2525
}, 5_000)
2626
})
2727
}
2828

2929
public async down(): Promise<void> {
30-
Logger.log('EmployeeNumber1616027432511 down')
30+
Logger.log('EmployeeNumber1729092660 down')
3131
}
3232
}

src/migrations/jobs/nonvalidfile.ts

Whitespace-only changes.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import readline from 'readline';
2+
3+
export function startLoader(message) {
4+
let currentFrame = 0;
5+
const spinnerFrames = ['-', '\\', '|', '/'];
6+
7+
const loaderInterval = setInterval(() => {
8+
readline.cursorTo(process.stdout, 0);
9+
process.stdout.write(`${spinnerFrames[currentFrame]} ${message} `);
10+
currentFrame = (currentFrame + 1) % spinnerFrames.length;
11+
}, 100);
12+
13+
return loaderInterval;
14+
}
15+
16+
export function stopLoader(loaderInterval) {
17+
clearInterval(loaderInterval);
18+
readline.cursorTo(process.stdout, 0);
19+
process.stdout.clearLine(0);
20+
}
Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,17 @@
1-
import { DynamicModule, Logger, Module } from '@nestjs/common';
2-
import { glob } from 'glob';
3-
import chalk from 'chalk';
1+
import { DynamicModule, Module } from '@nestjs/common';
42
import { MigrationsService } from './migrations.service';
3+
import { RunMigrationService } from './run-migration.service';
54

65
@Module({
7-
imports: [],
86
providers: [
97
MigrationsService,
8+
RunMigrationService,
109
],
1110
})
1211
export class MigrationsModule {
1312
public static async register(): Promise<DynamicModule> {
14-
const jobs = [];
15-
const files = await glob(`./jobs/*.js`, {
16-
cwd: __dirname,
17-
root: __dirname,
18-
});
19-
20-
for (const file of files) {
21-
const migration = await import(`${__dirname}/${file}`);
22-
23-
if (!migration.default) {
24-
Logger.log(chalk.yellow(`Migration ${chalk.bold('<' + file + '>')} does not have a default export !`));
25-
return;
26-
}
27-
28-
jobs.push(migration.default);
29-
}
30-
3113
return {
3214
module: this,
33-
providers: [
34-
...Reflect.getMetadata('providers', this),
35-
...jobs,
36-
],
3715
}
3816
}
3917
}
Lines changed: 61 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,100 @@
11
import { Injectable, Logger, OnModuleInit } from '@nestjs/common'
2-
import { InjectModel } from '@nestjs/mongoose'
3-
import { Model } from 'mongoose'
42
import { glob } from 'glob'
5-
import readline from 'readline'
63
import chalk from 'chalk'
7-
8-
function startLoader(message) {
9-
let currentFrame = 0;
10-
const spinnerFrames = ['-', '\\', '|', '/'];
11-
12-
const loaderInterval = setInterval(() => {
13-
readline.cursorTo(process.stdout, 0);
14-
process.stdout.write(`${spinnerFrames[currentFrame]} ${message} `);
15-
currentFrame = (currentFrame + 1) % spinnerFrames.length;
16-
}, 100);
17-
18-
return loaderInterval;
19-
}
20-
21-
function stopLoader(loaderInterval) {
22-
clearInterval(loaderInterval);
23-
readline.cursorTo(process.stdout, 0);
24-
process.stdout.clearLine(0);
25-
}
4+
import { ModuleRef } from '@nestjs/core'
5+
import { startLoader, stopLoader } from './migration-loader.function'
6+
import { readFile, writeFile } from 'fs/promises'
267

278
@Injectable()
289
export class MigrationsService implements OnModuleInit {
2910
private readonly logger = new Logger(`${chalk.bold.red(MigrationsService.name)}\x1b[33m`)
3011

3112
protected migrations = new Map<string, any>()
3213

33-
public constructor() { }
14+
public constructor(private readonly moduleRef: ModuleRef) { }
3415

3516
public async onModuleInit() {
36-
await this.runMigrations()
37-
}
38-
39-
public async runMigrations() {
17+
await this._checkMigrationLockFile()
4018
this.logger.log(chalk.yellow('Checking migrations files...'));
41-
await this._loadMigrationsFiles()
42-
19+
await this._loadMigrationsFiles();
4320

4421
const loader = startLoader('Migration en cours...');
4522
await this._executeMigrations();
4623
stopLoader(loader);
4724
}
4825

26+
private async _checkMigrationLockFile() {
27+
let migrationTimestamp = 0
28+
29+
try {
30+
const migration = await readFile('./migrations.lock', 'utf-8')
31+
console.log('migration', migration)
32+
} catch (error) {
33+
this.logger.warn(chalk.red('No migration lock file found.'))
34+
}
35+
36+
if (migrationTimestamp === 0) {
37+
try {
38+
await writeFile('./migrations.lock', migrationTimestamp.toString())
39+
this.logger.log(chalk.green('Migration lock file created.'))
40+
} catch (error) {
41+
this.logger.error(chalk.red('Error while creating migration lock file !'))
42+
}
43+
}
44+
}
45+
4946
private async _loadMigrationsFiles() {
50-
const files = await glob(`./migrations/*.js`, {
47+
const currentTimestamp = 1729092659
48+
// const currentTimestamp = Date.now()
49+
let files = await glob(`./jobs/*.js`, {
5150
cwd: __dirname,
5251
root: __dirname,
5352
});
5453

54+
files = files.filter((file) => {
55+
const [timestampMatch] = file.match(/\d{10,}/) || []
56+
57+
if (!timestampMatch) {
58+
this.logger.warn(chalk.yellow(`Migration ${chalk.bold('<' + file.replace(/.js$/, '') + '>')} does not have a timestamp in the filename !`));
59+
return;
60+
}
61+
62+
if (parseInt(timestampMatch) < currentTimestamp) {
63+
this.logger.debug(chalk.yellow(`Migration ${chalk.bold('<' + file.replace(/.js$/, '') + '>')} are already executed !`));
64+
return false;
65+
}
66+
67+
return true
68+
})
69+
70+
files = files.sort((a, b) => {
71+
const [aTimestamp] = a.match(/\d{10,}/) || []
72+
const [bTimestamp] = b.match(/\d{10,}/) || []
73+
74+
return parseInt(aTimestamp) - parseInt(bTimestamp)
75+
})
76+
5577
for (const file of files) {
5678
const migration = await import(`${__dirname}/${file}`);
79+
const [timestampMatch] = file.match(/\d{10,}/) || []
80+
81+
console.log('file', timestampMatch)
5782

5883
if (!migration.default) {
5984
this.logger.log(chalk.yellow(`Migration ${chalk.bold('<' + file + '>')} does not have a default export !`));
6085
return;
6186
}
6287

63-
this.migrations.set(file, migration)
88+
this.migrations.set(timestampMatch, migration)
6489
}
6590
}
6691

6792
private async _executeMigrations() {
68-
console.log('this.migrations.keys()', this.migrations.keys())
6993
for (const key of this.migrations.keys()) {
94+
this.logger.log(chalk.yellow(`Running migration ${chalk.bold('<' + key + '>')}...`));
95+
7096
const migration = this.migrations.get(key);
71-
const instance = new migration.default();
97+
const instance = await this.moduleRef.create(migration.default);
7298

7399
if (typeof instance.up !== 'function') {
74100
this.logger.log(chalk.yellow(`Migration ${chalk.bold('<' + key + '>')} does not have an up method !`));
@@ -78,5 +104,7 @@ export class MigrationsService implements OnModuleInit {
78104
this.logger.log(chalk.yellow(`Running migration ${chalk.bold('<' + key + '>')}...`));
79105
await instance.up();
80106
}
107+
108+
this.logger.log(chalk.green('All migrations done.'));
81109
}
82110
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { Injectable } from "@nestjs/common";
2+
3+
@Injectable()
4+
export class RunMigrationService {
5+
6+
}

0 commit comments

Comments
 (0)