A NestJS module for integrating Knex
npm install @knaadh/nestjs-knex knex
Then install one of the following database drivers according to your database type
npm install pg
npm install pg-native
npm install sqlite3
npm install better-sqlite3
npm install mysql
npm install mysql2
npm install oracledb
npm install tedious
Import the KnexModule module and pass an options
object to initialize it. You can pass options
object using the usual methods for custom providers as shown below:
import { KnexModule } from '@knaadh/nestjs-knex';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
// Method #1: Pass options object
KnexModule.register({
tag: 'DB_1',
config: {
client: 'better-sqlite3',
connection: {
filename: './demo.db',
},
},
}),
// Method #2: useFactory()
KnexModule.registerAsync({
tag: 'DB_2',
useFactory: () => ({
config: {
client: 'better-sqlite3',
connection: {
filename: './demo.db',
},
},
}),
}),
// Method #3: useClass()
KnexModule.registerAsync({
tag: 'DB_3',
useClass: KnexConfigService,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
export class KnexConfigService {
create = () => {
return {
config: {
client: 'better-sqlite3',
connection: {
filename: './demo.db',
},
},
};
};
}
You can inject the Knex
instances using their respective tag
specified in the configurations
import { Knex } from 'knex';
import { Inject, Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
constructor(
@Inject('DB_1') private knexDB1: Knex,
@Inject('DB_2') private knexDB2: Knex
) {}
async getData() {
const books = await this.knexDB1('books').select('title', 'author');
const authors = await this.knexDB2('authors').select('id', 'name');
return {
books: books,
authors: authors,
};
}
}
A KnexModule option
object has the following interface:
export interface KnexOptions {
config: Knex.Config;
}
config:
configuration object for Knex as described here
This package is MIT licensed