import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common"; import { Pool } from "pg"; import { migrationsDir } from "@workspace/schema/migrations"; import { drizzle, NodePgDatabase, migrate, projects, tasks, projectsRelations, tasksRelations, } from "@workspace/schema"; const DEFAULT_PG_PORT = 5432; @Injectable() export class DrizzleService implements OnModuleInit, OnModuleDestroy { private pool: Pool; public db: NodePgDatabase>; constructor() { this.pool = new Pool({ host: String(process.env.POSTGRES_HOST ?? "localhost"), port: Number(process.env.POSTGRES_PORT ?? DEFAULT_PG_PORT), user: String(process.env.POSTGRES_USER ?? "postgres"), password: String(process.env.POSTGRES_PASSWORD ?? "postgres"), database: String(process.env.POSTGRES_DB ?? "work_hub"), }); this.db = drizzle(this.pool, { schema: { projects, tasks, projectsRelations, tasksRelations }, }); } async onModuleInit() { await migrate(this.db, { migrationsFolder: migrationsDir, }); } async onModuleDestroy() { await this.pool.end(); } }