From c5b4b3e83b26a2f519ce68fd0c501bc00a97f8a2 Mon Sep 17 00:00:00 2001 From: Mathis Date: Wed, 21 Aug 2024 14:29:43 +0200 Subject: [PATCH] =?UTF-8?q?Ajoute=20la=20gestion=20de=20la=20base=20de=20d?= =?UTF-8?q?onn=C3=A9es=20PostgreSQL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cette modification introduit la connexion à la base de données PostgreSQL via les clients de migration et standard. Elle inclut également l'importation du module de configuration pour récupérer les paramètres de la base de données et assure le nettoyage des connexions à la destruction du module. --- apps/backend/src/app/db/db.module.ts | 3 ++ apps/backend/src/app/db/db.service.ts | 50 +++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) 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); + } +}