Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add prisma connection #59

Merged
merged 1 commit into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}
}
Loading