Ajoute la gestion de la base de données PostgreSQL

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.
This commit is contained in:
Mathis H (Avnyr) 2024-08-21 14:29:43 +02:00
parent fef0229cba
commit c5b4b3e83b
No known key found for this signature in database
GPG Key ID: FF69BF8BF95CDD58
2 changed files with 51 additions and 2 deletions

View File

@ -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 {}

View File

@ -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<Record<string, postgres.PostgresType>>;
private standardClient: postgres.Sql<Record<string, postgres.PostgresType>>;
constructor(private configService: ConfigService) {}
async onModuleInit() {
const dbConfig = {
host: this.configService.get<string>("POSTGRES_HOST"),
port: Number(this.configService.get<string>("POSTGRES_PORT")),
database: this.configService.get<string>("POSTGRES_DATABASE"),
user: this.configService.get<string>("POSTGRES_USER"),
password: this.configService.get<string>("POSTGRES_PASSWORD"),
ssl: Boolean(this.configService.get<string>("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);
}
}