nestjs-knex-module
v0.1.2
Published
This is a dynamic module to use [Knex](https://knexjs.org/) in a Nestjs application. It follows [this guide](https://dev.to/nestjs/build-a-nestjs-module-for-knex-js-or-other-resource-based-libraries-in-5-minutes-12an), but has some minimal changes regardi
Downloads
1
Readme
Nestjs Knex Module
This is a dynamic module to use Knex in a Nestjs application. It follows this guide, but has some minimal changes regarding typings.
It is a dynamic module, so it can be configured like this:
@Module({
imports: [KnexModule.register({
client: 'pg',
connection: {
host: 'localhost',
user: 'myuser',
password: 'mypassword',
database: 'mydb',
port: 5432,
}
})],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Alternatively you can also create a file knexfile.ts
:
import { Knex } from 'knex';
let KnexConfig: Knex.Config = {
client: 'pg',
connection: {
host: 'localhost',
user: 'myuser',
password: 'mypassword',
database: 'mydb',
port: 5432,
},
migrations: {
directory: 'src/migrations',
tableName: 'migrations',
extension: 'ts'
},
seeds: {
directory: 'src/seeders',
extension: 'ts'
}
};
export default KnexConfig
And import this file in your module:
import KnexConfig from '../knexfile';
@Module({
imports: [
KnexModule.register({...KnexConfig}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Then you can inject Knex in your services:
@Injectable()
export class UsersService {
constructor(@Inject(KNEX_CONNECTION) private readonly knex: Knex) {}
getAll() {
return this.knex<User>('users').select(['*']);
}
}