@quazex/nestjs-postgres
v1.0.1
Published
NestJS module for Postgres library
Maintainers
Readme
NestJS Postgres Module
Core features:
- Based on postgres library for NodeJS;
- Covered with unit and e2e tests;
- Basic module without unnecessary boilerplate.
Installation
npm install @quazex/nestjs-postgres postgresUsage
Importing the Module
import { Module } from '@nestjs/common';
import { PostgresModule } from '@quazex/nestjs-postgres';
@Module({
imports: [
PostgresModule.forRoot({
host: 'localhost',
port: 5432,
user: 'test',
password: 'test',
database: 'test',
}),
],
})
export class AppModule {}Injecting the Client
import { Injectable } from '@nestjs/common';
import { InjectPostgres } from '@quazex/nestjs-postgres';
import type { Sql } from 'postgres';
@Injectable()
export class DatabaseService {
constructor(@InjectPostgres() private readonly sql: Sql) {}
async insert(document: object) {
await this.sql`INSERT INTO table ${this.sql(document)}`;
}
async select(id: string) {
const [row] = await this.sql`SELECT * FROM table WHERE id = ${id}`;
return row;
}
}Async Configuration
import { Module } from '@nestjs/common';
import { PostgresModule } from '@quazex/nestjs-postgres';
@Module({
imports: [
PostgresModule.forRootAsync({
useFactory: (config: SomeConfigProvider) => ({
host: config.PG_HOST,
port: config.PG_PORT,
user: config.PG_USER,
password: config.PG_PASSWORD,
database: config.PG_DATABASE,
}),
inject: [
SomeConfigProvider,
],
}),
],
})
export class AppModule {}Connection and graceful shutdown
By default, this module doesn't manage the client connection on application shutdown. You can read more about lifecycle hooks on the NestJS documentation page.
// main.ts
const app = await NestFactory.create(AppModule);
app.enableShutdownHooks();
await app.listen(process.env.PORT ?? 3000);// app.bootstrap.ts
import { Injectable, OnApplicationShutdown } from '@nestjs/common';
import { InjectPostgres } from '@quazex/nestjs-postgres';
import type { Sql } from 'postgres';
@Injectable()
export class AppBootstrap implements OnApplicationShutdown {
constructor(@InjectPostgres() private readonly sql: Sql) {}
public async onApplicationShutdown(): Promise<void> {
await this.sql.end();
}
}License
MIT
