diff --git a/apps/backend/src/app/db/db.module.ts b/apps/backend/src/app/db/db.module.ts index e2b1172..405c8a0 100644 --- a/apps/backend/src/app/db/db.module.ts +++ b/apps/backend/src/app/db/db.module.ts @@ -1,7 +1,10 @@ import { Module } from "@nestjs/common"; import { DbService } from "./db.service"; +import {ConfigModule} from "@nestjs/config"; @Module({ + imports: [ConfigModule], providers: [DbService], + exports: [DbService] }) export class DbModule {} diff --git a/apps/backend/src/app/db/db.service.ts b/apps/backend/src/app/db/db.service.ts index 56bb509..8093944 100644 --- a/apps/backend/src/app/db/db.service.ts +++ b/apps/backend/src/app/db/db.service.ts @@ -1,4 +1,50 @@ -import { Injectable } from "@nestjs/common"; +import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; +import { drizzle } from "drizzle-orm/postgres-js"; +import { migrate } from "drizzle-orm/postgres-js/migrator"; +import postgres from "postgres"; @Injectable() -export class DbService {} +export class DbService { + private migrationClient: postgres.Sql>; + private standardClient: postgres.Sql>; + + constructor(private configService: ConfigService) {} + + async onModuleInit() { + const dbConfig = { + host: this.configService.get("POSTGRES_HOST"), + port: Number(this.configService.get("POSTGRES_PORT")), + database: this.configService.get("POSTGRES_DATABASE"), + user: this.configService.get("POSTGRES_USER"), + password: this.configService.get("POSTGRES_PASSWORD"), + ssl: Boolean(this.configService.get("POSTGRES_SSL")), + }; + + this.migrationClient = postgres({ + ...dbConfig, + max: 1, + }); + + this.standardClient = postgres({ + ...dbConfig, + }); + } + + //onModuleDestroy + async onModuleDestroy() { + await this.migrationClient.end(); + await this.standardClient.end(); + } + + getMigrationClient() { + return migrate(drizzle(this.migrationClient), { + migrationsFolder: "./migrations", + migrationsSchema: "public", + }); + } + + use() { + return drizzle(this.standardClient); + } +}