Setup
Objection Setup
Incase, you want to use objection package in your application (if you are not using this boilerplate), you can do so by install @squareboat/nestjs-objection package seperately.
npm i @squareboat/nestjs-objection --save
To register ObjectionModule with your app, import the module inside AppModule.
Static Registration
StorageModuleis added to global scope by default.
The configuration objection of database is same as knexfile.js configuration only.
import { Module } from "@nestjs/common";
import { ObjectionModule } from "@squareboat/nestjs-objection";
@Module({
imports: [
ObjectionModule.register({
isGlobal: true,
default: "postgres",
connections: {
postgres: {
client: "pg",
debug: !!+process.env.DB_DEBUG,
connection: {
host: process.env.DB_HOST,
port: +process.env.DB_PORT,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
charset: "utf8",
},
},
},
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
Recommended Way
Use ConfigModule provided by NestJS to load configurations. To learn about ConfigModule, click here.
1. Create database.ts file
import { registerAs } from "@nestjs/config";
export default registerAs("db", () => ({
isGlobal: true,
default: "postgres",
connections: {
postgres: {
client: "pg",
debug: !!+process.env.DB_DEBUG,
connection: {
host: process.env.DB_HOST,
port: +process.env.DB_PORT,
database: process.env.DB_DATABASE,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
charset: "utf8",
},
validateQuery: 'select 1'
},
},
}));
2. Register ConfigModule
import { Module } from "@nestjs/common";
import database from "@config/database";
import { ConfigModule } from "@nestjs/config";
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
expandVariables: true,
load: [database],
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
#3. Register Async StorageModule
Add following snippet to the imports array. ConfigService is importable from @nestjs/config module.
ObjectionModule.registerAsync({
imports: [ConfigService],
useFactory: (config: ConfigService) => {
return config.get("db");
},
inject: [ConfigService],
});
Once the setup is done, you can retrieve connection instances of knex using the following approach.
import {
CustomQueryBuilder,
ObjectionService,
} from "@squareboat/nestjs-objection";
const connection = ObjectionService.connection("postgres");
Wooho! If you are here then it means that you have successfully configured @squareboat/nestjs-objection package.