Skip to the content.

Nest Logo

Pagination included Knex module for Nest

Nrwl Nx

CodeFactor Grade npm npm

Table of Contents

Installation

npm install @mithleshjs/knex-nest knex

Then install one of the following database drivers according to your database type

npm install pg
npm install sqlite3
npm install mysql
npm install mysql2
npm install oracledb
npm install tedious

Usage

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 { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { KnexModule } from '@mithleshjs/knex-nest';

@Module({
  imports: [
    KnexModule.register({
      config: {
        client: 'mysql',
        connection: {
          host: '127.0.0.1',
          port: 3306,
          user: 'your_database_user',
          password: 'your_database_password',
          database: 'your_database',
        },
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { KnexModule } from '@mithleshjs/knex-nest';

@Module({
  imports: [
    KnexModule.registerAsync({
      useFactory: () => ({
        config: {
          client: 'mysql',
          connection: {
            host: '127.0.0.1',
            port: 3306,
            user: 'your_database_user',
            password: 'your_database_password',
            database: 'your_database',
          },
        },
      }),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { KnexModule } from '@mithleshjs/knex-nest';
import { DbConfigService } from '../db-config.service';

@Module({
  imports: [
    KnexModule.registerAsync({
      useClass: DbConfigService,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
export class DbConfigService {
  createKnexModuleOptions = () => {
    return {
      config: {
        client: 'mysql',
        connection: {
          host: '127.0.0.1',
          port: 3306,
          user: 'your_database_user',
          password: 'your_database_password',
          database: 'your_database',
        },
      },
    };
  };
}
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { KnexModule } from '@mithleshjs/knex-nest';
import { DbConfigService } from '../db-config.service';

@Module({
  imports: [
    KnexModule.registerAsync({
      useExisting: AliasedDbConfigService,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Use the InjectKnex() decorator to inject the Knex connection as local property to access Knex API object directly. See the example below.

import { Injectable } from '@nestjs/common';
import { InjectKnex } from '@mithleshjs/knex-nest';
import { Knex } from 'knex';

@Injectable()
export class AppService {
  constructor(@InjectKnex() readonly knex: Knex) {}

  getUsers() {
    return this.knex('users').select('id', 'name')
  }
}

Configuration

A KnexModule option object has the following interface:

export interface IKnexModuleOptions {
  config: Knex.Config;
  configTag?: string;
}

Multiple Databases

You can connect as many databases as you want, you just need to pass a unique configTag for each instance.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { KnexModule } from '@mithleshjs/knex-nest';

@Module({
  imports: [
    KnexModule.register({
      config: {
        client: 'mysql',
        connection: {
          host: '127.0.0.1',
          port: 3306,
          user: 'your_database_user',
          password: 'your_database_password',
          database: 'your_database',
        },
      },
      configTag: 'mysql8',
    }),
    KnexModule.register({
      config: {
        client: 'pg',
        connection: process.env.PG_CONNECTION_STRING,
        searchPath: ['knex', 'public'],
      },
      configTag: 'postgres12',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Pass the configTag value in InjectKnex() decorator to inject the specific Knex connection. See the example below.

import { Injectable } from '@nestjs/common';
import { InjectKnex } from '@mithleshjs/knex-nest';
import { Knex } from 'knex';

@Injectable()
export class AppService {
  constructor(
    @InjectKnex('postgres12') readonly knexPg: Knex,
    @InjectKnex('mysql8') readonly knexSQL: Knex
  ) {}

  getUsers() {
    return this.knexPg('users').select('id', 'name')
  }

  getAuthors() {
    return this.knexSQL('authors').select('id', 'name')
  }
}

Pagination

The pagination functionality has been rewritten as a separate utility as Knex plugin API was not stable. Pagination utility supports both offset and cursor based pagination. You can learn how it was designed from here.

Documentation

Acknowledgement

License

Knex-Nest is MIT licensed.