Recipe-app main
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService
|
||||
extends PrismaClient
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
private readonly logger = new Logger(PrismaService.name);
|
||||
|
||||
async onModuleInit() {
|
||||
const maxAttempts = 10;
|
||||
const delayMs = 3000;
|
||||
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
try {
|
||||
this.logger.log(
|
||||
`Försöker ansluta till databasen (försök ${attempt}/${maxAttempts})...`,
|
||||
);
|
||||
|
||||
await this.$connect();
|
||||
|
||||
this.logger.log('Databasanslutning etablerad.');
|
||||
return;
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : 'Okänt fel';
|
||||
|
||||
this.logger.warn(
|
||||
`Databasanslutning misslyckades på försök ${attempt}/${maxAttempts}: ${message}`,
|
||||
);
|
||||
|
||||
if (attempt === maxAttempts) {
|
||||
this.logger.error(
|
||||
'Kunde inte ansluta till databasen efter maximalt antal försök.',
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user