Skip to content

Commit 11a2b62

Browse files
committed
Refactor migrations module and service
1 parent 9e23639 commit 11a2b62

File tree

4 files changed

+50
-20
lines changed

4 files changed

+50
-20
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.module.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import { DynamicModule, Module } from '@nestjs/common';
22
import { MigrationsService } from './migrations.service';
3-
import { RunMigrationService } from './run-migration.service';
43

54
@Module({
65
providers: [
76
MigrationsService,
8-
RunMigrationService,
97
],
108
})
119
export class MigrationsModule {

src/migrations/migrations.service.ts

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,24 @@ import { ModuleRef } from '@nestjs/core'
55
import { startLoader, stopLoader } from './migration-loader.function'
66
import { readFile, writeFile } from 'fs/promises'
77
import { posix } from 'path'
8+
import { ConfigService } from '@nestjs/config'
9+
import { Connection } from 'mongoose'
10+
import { InjectConnection } from '@nestjs/mongoose'
811

912
@Injectable()
1013
export class MigrationsService implements OnModuleInit {
1114
private readonly logger = new Logger(`${chalk.bold.red(MigrationsService.name)}\x1b[33m`)
1215

16+
protected lockLocation: string
1317
protected migrations = new Map<string, any>()
1418

15-
protected lockLocation = posix.join(process.cwd(), 'migrations.lock')
19+
public constructor(
20+
@InjectConnection() private readonly mongo: Connection,
21+
private readonly moduleRef: ModuleRef,
22+
private readonly config: ConfigService,
1623

17-
public constructor(private readonly moduleRef: ModuleRef) {
24+
) {
25+
this.lockLocation = posix.join(this.config.get('factorydrive.options.disks.local.config.root', '/tmp'), 'migrations.lock')
1826
}
1927

2028
public async onModuleInit() {
@@ -33,22 +41,43 @@ export class MigrationsService implements OnModuleInit {
3341
let currentTimestamp = 0
3442

3543
try {
36-
const migration = await readFile(this.lockLocation, 'utf-8')
37-
currentTimestamp = parseInt(migration, 10)
44+
const migration = await readFile(this.lockLocation, 'utf-8');
45+
currentTimestamp = parseInt(migration, 10);
3846
this.logger.log(chalk.blue(`Migration lock state is <${currentTimestamp}> !`));
3947
} catch (error) {
40-
this.logger.warn(chalk.red('No migration lock file found.'))
48+
this.logger.warn(chalk.red('No migration lock file found.'));
4149
}
4250

51+
const dbMigration = await this.mongo.collection('migrations').findOne({}, { sort: { timestamp: -1 } });
52+
4353
if (currentTimestamp === 0) {
44-
try {
45-
await writeFile(this.lockLocation, currentTimestamp.toString())
46-
this.logger.log(chalk.green('Migration lock file created.'))
47-
} catch (error) {
48-
this.logger.error(chalk.red('Error while creating migration lock file !'))
54+
if (dbMigration) {
55+
try {
56+
this.logger.warn(chalk.yellow('No migration lock file found. Creating one with the last migration timestamp...'));
57+
await writeFile(this.lockLocation, dbMigration.timestamp.toString());
58+
this.logger.log(chalk.green('Migration lock file created.'));
59+
} catch (error) {
60+
this.logger.error(chalk.red('Error while creating migration lock file !'));
61+
}
62+
} else {
63+
try {
64+
await writeFile(this.lockLocation, currentTimestamp.toString());
65+
this.logger.log(chalk.green('Migration lock file created.'));
66+
} catch (error) {
67+
this.logger.error(chalk.red('Error while creating migration lock file !'));
68+
}
4969
}
5070
}
5171

72+
if (!dbMigration && currentTimestamp !== 0) {
73+
this.logger.error(chalk.red('Database is not up to date with the migrations files !'));
74+
await this.mongo.collection('migrations').insertOne({
75+
timestamp: currentTimestamp,
76+
comment: 'Synchronization with the migration lock file',
77+
});
78+
this.logger.log(chalk.green('Database updated with the current migration lock file !'));
79+
}
80+
5281
return currentTimestamp
5382
}
5483

@@ -99,6 +128,11 @@ export class MigrationsService implements OnModuleInit {
99128
return;
100129
}
101130

131+
if (!this.migrations.size) {
132+
this.logger.log(chalk.blue('No migrations to execute.'));
133+
return;
134+
}
135+
102136
for (const key of this.migrations.keys()) {
103137
const [migrationTimestamp] = key.match(/\d{10,}/) || []
104138

@@ -120,7 +154,11 @@ export class MigrationsService implements OnModuleInit {
120154
}
121155

122156
try {
123-
await writeFile('./migrations.lock', migrationTimestamp);
157+
await writeFile(this.lockLocation, migrationTimestamp);
158+
await this.mongo.collection('migrations').insertOne({
159+
timestamp: parseInt(migrationTimestamp),
160+
comment: `Migration ${key} executed`,
161+
})
124162
this.logger.log(chalk.blue(`Migration ${chalk.bold('<' + key + '>')} done.`));
125163
} catch (e) {
126164
this.logger.error(chalk.red(`Error while updating migration lock file !`));

src/migrations/run-migration.service.ts

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

0 commit comments

Comments
 (0)