File size: 1,171 Bytes
4acc19f
 
3f1a51c
1e3c043
4acc19f
 
 
 
 
 
1e3c043
 
 
 
 
 
 
3f1a51c
1e3c043
4acc19f
1e3c043
 
3f1a51c
4acc19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { INestApplication, Injectable, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { Pool } from 'pg';

@Injectable()
export class PrismaService implements OnModuleDestroy {
  public prisma: PrismaClient;

  constructor() {
    // Prisma 7: Use adapter for Supabase/Neon PostgreSQL with SSL configuration
    const isCloudDatabase =
      process.env.DATABASE_URL?.includes('supabase') ||
      process.env.DATABASE_URL?.includes('neon') ||
      process.env.NODE_ENV === 'production';

    const pool = new Pool({
      connectionString: process.env.DATABASE_URL,
      ssl: isCloudDatabase ? { rejectUnauthorized: false } : undefined,
    });

    const adapter = new PrismaPg(pool);
    this.prisma = new PrismaClient({ adapter });
  }

  getClient(): PrismaClient {
    return this.prisma;
  }

  async onModuleDestroy() {
    await this.prisma.$disconnect();
  }

  async enableShutdownHooks(app: INestApplication) {
    // Replace the Prisma beforeExit with Node.js process beforeExit
    process.on('beforeExit', async () => {
      await app.close();
    });
  }
}