I want to use NestJS framework. But prefer to write SQL queries by myself, and not use the heavy interface of ORMs.
I found some tutorials with examples of direct access to database, but they don't use the injection mechanism of NestJS. So, I'm trying to learn how to write a thin layers of controller and services provider which gives me the freedom to supply the query as a text parameter. Will appriciate your advices
CodePudding user response:
Let's assume that you want to use plain Postgres with nestJs (Without ORM).
You can perform the following steps :
Create A Separate Database Module And then create and inject Custom Provider
import { Module } from "@nestjs/common";
import { Pool } from "pg";
import { PG_CONNECTION } from "../constants";
export const PG_CONNECTION = 'PG_CONNECTION';
const dbProvider = {
provide: PG_CONNECTION,
useValue: new Pool({
user: "postgres",
host: "localhost",
database: "somedb",
password: "meh",
port: 5432,
}),
};
@Module({
providers: [dbProvider],
exports: [dbProvider],
})
export class DbModule {}
NOTE: Do export your custom Provider because we need this provider(service) in other modules.
After That, you can easily inject that provider(service) into any other module by Just Importing DbModule
@Module({
providers: [AppService],
imports : [DbModule]
})
export class AppModule {}
After That you can easily inject the provider and can perform database operations with plain SQL query
import { Injectable, Inject } from '@nestjs/common';
import { PG_CONNECTION from './constants';
@Injectable()
export class AppService {
constructor(@Inject(PG_CONNECTION) private conn: any) {}
async getUsers() {
const res = await this.conn.query('SELECT * FROM users');
return res.rows;
}
}
Hope this helps!
You can further read this article for better explanation. REFERENCE : https://medium.com/@calleja.justin/using-plain-pg-with-nest-js-617ec32ec2c4