Skip to content

Instantly share code, notes, and snippets.

@kyzsuukii
Created November 23, 2024 16:26
Show Gist options
  • Save kyzsuukii/1f284ba3cb9549265d6d7d9be59d761b to your computer and use it in GitHub Desktop.
Save kyzsuukii/1f284ba3cb9549265d6d7d9be59d761b to your computer and use it in GitHub Desktop.
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { drizzle, NodePgDatabase } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import * as schema from 'src/drizzle/drizzle.schema';
@Injectable()
export class Drizzle implements OnModuleInit, OnModuleDestroy {
private pool: Pool;
public db: NodePgDatabase<typeof schema>;
constructor(private readonly config: ConfigService) {}
onModuleInit() {
const dbUrl = this.config.get<string>('DATABASE_URL');
const isProd = this.config.get<string>('NODE_ENV');
this.pool = new Pool({
connectionString: dbUrl,
});
this.db = drizzle(this.pool, {
schema,
logger: !isProd,
});
}
async onModuleDestroy() {
if (this.pool) {
await this.pool.end();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment