0.1.2 • Published 2 years ago

nestjs-knex-module v0.1.2

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

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

2 years ago

0.1.1

3 years ago

0.1.0

3 years ago