refactor source code
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
import { Global, Module } from '@nestjs/common'
|
||||
import { PrismaService } from './prisma.service'
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
|
||||
@@ -3,13 +3,13 @@ import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
} from '@nestjs/common'
|
||||
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit {
|
||||
private readonly logger = new Logger(PrismaService.name);
|
||||
private readonly logger = new Logger(PrismaService.name)
|
||||
constructor() {
|
||||
super({
|
||||
log: [
|
||||
@@ -35,44 +35,44 @@ export class PrismaService extends PrismaClient implements OnModuleInit {
|
||||
maxWait: 30 * 1000,
|
||||
timeout: 60 * 1000,
|
||||
},
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
this.logger.log('Try to connect database...');
|
||||
this.logger.log('Try to connect database...')
|
||||
|
||||
const maxRetry = parseInt(process.env.PRISMA_MAX_RETRY as string) ?? 3;
|
||||
const retryDelay = 10000;
|
||||
const maxRetry = parseInt(process.env.PRISMA_MAX_RETRY as string) ?? 3
|
||||
const retryDelay = 10000
|
||||
|
||||
for (let attempt = 1; attempt <= maxRetry; attempt++) {
|
||||
try {
|
||||
await this.$connect();
|
||||
this.logger.log('Connected.');
|
||||
return;
|
||||
await this.$connect()
|
||||
this.logger.log('Connected.')
|
||||
return
|
||||
} catch (error) {
|
||||
if (attempt < maxRetry) {
|
||||
this.logger.warn(
|
||||
`Connection attempt ${attempt} failed. Retrying in ${retryDelay}ms...`,
|
||||
);
|
||||
await this.delay(retryDelay);
|
||||
)
|
||||
await this.delay(retryDelay)
|
||||
} else {
|
||||
this.logger.error(
|
||||
`Failed to connect to the database after ${maxRetry} attempts.`,
|
||||
);
|
||||
throw error;
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
async enableShutdownHooks(app: INestApplication) {
|
||||
this.$on('beforeExit' as never, async () => {
|
||||
this.logger.log('Wait for application closing...');
|
||||
await app.close();
|
||||
});
|
||||
this.logger.log('Wait for application closing...')
|
||||
await app.close()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user