feat: services database, reminders, taskprocessor init
This commit is contained in:
64
services/database.ts
Normal file
64
services/database.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
// Singleton pattern pour Prisma Client
|
||||
declare global {
|
||||
var __prisma: PrismaClient | undefined;
|
||||
}
|
||||
|
||||
// Créer une instance unique de Prisma Client
|
||||
export const prisma = globalThis.__prisma || new PrismaClient({
|
||||
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||
});
|
||||
|
||||
// En développement, stocker l'instance globalement pour éviter les reconnexions
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
globalThis.__prisma = prisma;
|
||||
}
|
||||
|
||||
// Fonction pour tester la connexion
|
||||
export async function testDatabaseConnection(): Promise<boolean> {
|
||||
try {
|
||||
await prisma.$connect();
|
||||
console.log('✅ Database connection successful');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('❌ Database connection failed:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Fonction pour fermer la connexion proprement
|
||||
export async function closeDatabaseConnection(): Promise<void> {
|
||||
try {
|
||||
await prisma.$disconnect();
|
||||
console.log('✅ Database connection closed');
|
||||
} catch (error) {
|
||||
console.error('❌ Error closing database connection:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Fonction utilitaire pour les transactions
|
||||
export async function withTransaction<T>(
|
||||
callback: (tx: PrismaClient) => Promise<T>
|
||||
): Promise<T> {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
return await callback(tx);
|
||||
});
|
||||
}
|
||||
|
||||
// Fonction pour nettoyer la base (utile pour les tests)
|
||||
export async function clearDatabase(): Promise<void> {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('Cannot clear database in production');
|
||||
}
|
||||
|
||||
await prisma.taskTag.deleteMany();
|
||||
await prisma.task.deleteMany();
|
||||
await prisma.tag.deleteMany();
|
||||
await prisma.syncLog.deleteMany();
|
||||
|
||||
console.log('🧹 Database cleared');
|
||||
}
|
||||
|
||||
// Export par défaut
|
||||
export default prisma;
|
||||
Reference in New Issue
Block a user