Skip to content

Commit

Permalink
Merge pull request #59 from panoratech/fix-docker
Browse files Browse the repository at this point in the history
feat: add prisma connection
  • Loading branch information
naelob authored Nov 3, 2023
2 parents f557932 + 31cacaf commit f4e0fc4
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/api/.env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
ENV=dev
DATABASE_URL=
JWT_SECRET="SECRET"
POSTGRES_HOST=
55 changes: 55 additions & 0 deletions packages/api/src/@core/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

private async waitForPostgres(): Promise<void> {
while (this.attempts < this.maxAttempts) {
try {
const client = new net.Socket();

await new Promise<void>((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();
}
}

0 comments on commit f4e0fc4

Please sign in to comment.