From 31cacaf12f77749fe444fe012a8fc0395aa4bfda Mon Sep 17 00:00:00 2001 From: nael Date: Fri, 3 Nov 2023 18:50:25 +0100 Subject: [PATCH] feat: add prisma connection --- packages/api/.env.example | 1 + .../api/src/@core/prisma/prisma.service.ts | 55 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/packages/api/.env.example b/packages/api/.env.example index 5cd31f371..b4be89b1e 100644 --- a/packages/api/.env.example +++ b/packages/api/.env.example @@ -1,3 +1,4 @@ ENV=dev DATABASE_URL= JWT_SECRET="SECRET" +POSTGRES_HOST= \ No newline at end of file diff --git a/packages/api/src/@core/prisma/prisma.service.ts b/packages/api/src/@core/prisma/prisma.service.ts index 359f950b7..6e543b279 100644 --- a/packages/api/src/@core/prisma/prisma.service.ts +++ b/packages/api/src/@core/prisma/prisma.service.ts @@ -1,9 +1,64 @@ import { Injectable, OnModuleInit } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; +import * as net from 'net'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit { + private readonly host: string = process.env.POSTGRES_HOST; + private readonly port: number = 5432; + private readonly maxAttempts: number = 60; + private readonly sleepInterval: number = 5000; + private attempts = 0; + + private sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); + } + + private async waitForPostgres(): Promise { + while (this.attempts < this.maxAttempts) { + try { + const client = new net.Socket(); + + await new Promise((resolve, reject) => { + client.setTimeout(1000); + + client.connect(this.port, this.host, () => { + console.log(`PostgreSQL port ${this.port} is available.`); + client.end(); + resolve(); + }); + + client.on('error', (err) => { + console.log( + `Attempt ${ + this.attempts + 1 + }: Waiting for PostgreSQL to become available on port ${ + this.port + }...`, + ); + client.destroy(); + reject(err); + }); + }); + + return; // Exit the function once connected + } catch (error) { + this.attempts++; + if (this.attempts >= this.maxAttempts) { + throw new Error( + `PostgreSQL port ${this.port} is not available after ${this.maxAttempts} attempts.`, + ); + } + await this.sleep(this.sleepInterval); + } + } + + // If the loop exits without connecting, throw an error + throw new Error(`PostgreSQL port ${this.port} was never available.`); + } + async onModuleInit() { + await this.waitForPostgres(); await this.$connect(); } }