55 lines
1.3 KiB
TypeScript
55 lines
1.3 KiB
TypeScript
import {
|
|
Injectable,
|
|
OnModuleInit,
|
|
OnModuleDestroy,
|
|
Logger,
|
|
} from '@nestjs/common';
|
|
import { PrismaClient } from '@prisma/client';
|
|
|
|
@Injectable()
|
|
export class PrismaService
|
|
extends PrismaClient
|
|
implements OnModuleInit, OnModuleDestroy
|
|
{
|
|
private readonly logger = new Logger(PrismaService.name);
|
|
|
|
constructor() {
|
|
super({
|
|
log: [
|
|
{ emit: 'event', level: 'query' },
|
|
{ emit: 'stdout', level: 'info' },
|
|
{ emit: 'stdout', level: 'warn' },
|
|
{ emit: 'stdout', level: 'error' },
|
|
],
|
|
});
|
|
}
|
|
|
|
async onModuleInit(): Promise<void> {
|
|
await this.$connect();
|
|
this.logger.log('Connected to database');
|
|
}
|
|
|
|
async onModuleDestroy(): Promise<void> {
|
|
await this.$disconnect();
|
|
this.logger.log('Disconnected from database');
|
|
}
|
|
|
|
async cleanDatabase(): Promise<void> {
|
|
if (process.env.NODE_ENV === 'production') {
|
|
throw new Error('Cannot clean database in production');
|
|
}
|
|
|
|
const models = Reflect.ownKeys(this).filter(
|
|
(key) => typeof key === 'string' && !key.startsWith('_') && !key.startsWith('$'),
|
|
);
|
|
|
|
for (const model of models) {
|
|
try {
|
|
await (this as any)[model]?.deleteMany?.();
|
|
} catch (error) {
|
|
// Ignore errors for non-model properties
|
|
}
|
|
}
|
|
}
|
|
}
|