npm.io
0.1.2 • Published 4 years ago

nestjs-knex-module

Licence
MIT
Version
0.1.2
Deps
2
Size
23 kB
Vulns
1
Weekly
0

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(['*']);
  }
}

Keywords