# Code coverage report for infrastructure/db/DatabaseConnection.js

# All files / infrastructure/db DatabaseConnection.js

0% Statements 0/25
0% Branches 0/8
0% Functions 0/5
0% Lines 0/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75

     const { PrismaClient } = require('@prisma/client');

    /**
     * Database Connection Wrapper
     * Manages Prisma Client lifecycle
     */
    class DatabaseConnection {
      constructor() {
        this.prisma = null;
      }

      /**
       * Initialize Prisma Client
       */
      async connect() {
        if (this.prisma) {
          console.log('⚠️  Prisma Client already connected');
          return;
        }

        try {
          this.prisma = new PrismaClient({
            log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
          });

          await this.prisma.$connect();
          console.log('✅ Prisma connected to PostgreSQL');
        } catch (error) {
          console.error('❌ Failed to connect to database:', error);
          throw error;
        }
      }

      /**
       * Get Prisma Client instance
       * @returns {PrismaClient}
       */
      getClient() {
        if (!this.prisma) {
          throw new Error('Database not connected. Call connect() first.');
        }
        return this.prisma;
      }

      /**
       * Close database connection
       */
      async disconnect() {
        if (this.prisma) {
          await this.prisma.$disconnect();
          console.log('🛑 Prisma disconnected');
          this.prisma = null;
        }
      }

      /**
       * Health check
       * @returns {Promise<boolean>}
       */
      async healthCheck() {
        try {
          await this.prisma.$queryRaw`SELECT 1`;
          return true;
        } catch (error) {
          console.error('❌ Database health check failed:', error);
          return false;
        }
      }
    }

    // Singleton instance
    const databaseConnection = new DatabaseConnection();

    module.exports = databaseConnection;