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:
parent
fef0229cba
commit
c5b4b3e83b
@ -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 {}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user