Skip to content

Tony133/nestjs-knexjs

Repository files navigation

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

Knexjs module for Nest framework (node.js) 😻

Installation

First install the module via yarn or npm or pnpm and do not forget to install the driver package as well:

  $ npm i --save nest-knexjs knex mysql     # for mysql/mariadb
  $ npm i --save nest-knexjs knex pg        # for postgresql
  $ npm i --save nest-knexjs knex sqlite    # for sqlite
  $ npm i --save nest-knexjs knex oracledb  # for oracledb

or

  $ yarn add nest-knexjs knex mysql     # for mysql/mariadb
  $ yarn add nest-knexjs knex pg        # for postgresql
  $ yarn add nest-knexjs knex sqlite    # for sqlite
  $ yarn add nest-knexjs knex oracledb  # for oracledb

or

  $ pnpm add nest-knexjs knex mysql     # for mysql/mariadb
  $ pnpm add nest-knexjs knex pg        # for postgresql
  $ pnpm add nest-knexjs knex sqlite    # for sqlite
  $ pnpm add nest-knexjs knex oracledb  # for oracledb

Table of Contents

Usage

KnexModule

KnexModule is the primary entry point for this package and can be used synchronously

@Module({
  imports: [
    KnexModule.forRoot({
      config: {
        client: 'mysql',
        version: '5.7',
        connection: {
          host: '127.0.0.1',
          user: 'root',
          password: 'root',
          database: 'test',
        },
      },
    }),
  ],
})

or asynchronously

@Module({
  imports: [
    KnexModule.forRootAsync({
      useFactory: () => ({
        config: {
          client: 'mysql',
          version: '5.7',
          connection: {
            host: '127.0.0.1',
            user: 'root',
            password: 'root',
            database: 'test',
          },
        },
      }),
    }),
  ],
})

Example of use

UsersService:

import { Injectable } from '@nestjs/common';
import { Knex } from 'knex';
import { InjectConnection } from 'nest-knexjs';

@Injectable()
export class UsersService {
  constructor(@InjectConnection() private readonly knex: Knex) {}

  async findAll() {
    const users = await this.knex.table('users');
    return { users };
  }
}

UsersController:

import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller()
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  async getAllUsers() {
    return await this.usersService.findAll();
  }
}

Multi Connections Database

@Module({
  imports: [
    KnexModule.forRootAsync(
      {
        useFactory: () => ({
          config: {
            client: 'mysql',
            version: '5.7',
            useNullAsDefault: true,
            connection: {
              host: '127.0.0.1',
              user: 'root',
              port: 3306,
              password: 'root',
              database: 'test1',
            },
            pool: {
              min: 2,
              max: 10,
            },
          },
        }),
      },
      'db1Connection',
    ),
    KnexModule.forRootAsync(
      {
        useFactory: () => ({
          config: {
            client: 'mysql',
            version: '5.7',
            useNullAsDefault: true,
            connection: {
              host: '127.0.0.1',
              user: 'root',
              port: 3307,
              password: 'root',
              database: 'test2',
            },
            pool: {
              min: 2,
              max: 10,
            },
          },
        }),
      },
      'db2Connection',
    ),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

Usage example with Multi Connection

PostService:

@Injectable()
export class PostService {
  constructor(
    @InjectConnection('db2Connection')
    private knexConnection: Knex,
  ) {}

  async create(createPostDto: CreatePostDto) {
    try {
      const post = await this.knexConnection.table('posts').insert({
        title: createPostDto.title,
        description: createPostDto.description,
      });

      return post;
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }

  async findAll() {
    const posts = await this.knexConnection.table('posts');
    return { posts };
  }
}

UsersService:

@Injectable()
export class UsersService {
  constructor(
    @InjectConnection('db1Connection')
    private knexConnection: Knex,
  ) {}

  async findAll() {
    const users = await this.knexConnection.table('users');
    return { users };
  }

  async create(createUserDto: CreateUserDto) {
    try {
      const users = await this.knexConnection.table('users').insert({
        firstName: createUserDto.firstName,
        lastName: createUserDto.lastName,
      });

      return { users };
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }
}

In knexfile.js update with your database configuration settings:

module.exports = {
  development: {
    client: 'mysql',
    version: '5.7',
    connection: {
      name: 'db1Connection',
      host: '127.0.0.1',
      user: 'root',
      port: 3306,
      password: 'root',
      database: 'test1',
    },
    migrations: {
      directory: './migrations/users',
      tableName: '[:name_file_migrations_users]',
    },
  },
  developmentTwo: {
    client: 'mysql',
    version: '5.7',
    connection: {
      name: 'db2Connection',
      host: '127.0.0.1',
      user: 'root',
      port: 3307,
      password: 'root',
      database: 'test2',
    },
    migrations: {
      directory: './migrations/posts',
      tableName: '[:name_file_migrations_posts]',
    },
  },
};

Run Migrations:

$ npx knex migrate:latest --env development

$ npx knex migrate:latest --env developmentTwo

Create Migrations

  $ npx knex init
  $ npx knex migrate:make [name_migrations]

Example file migrations:

exports.up = function(knex) {
  return knex.schema
    .createTable('users', function(table) {
      table.increments('id');
      table.string('firstName', 255).notNullable();
      table.string('lastName', 255).notNullable();
    })
    .createTable('products', function(table) {
      table.increments('id');
      table.string('name', 255).notNullable();
      table.decimal('price').notNullable();
    });
};

exports.down = function (knex) {
  return knex.schema.dropTable('products').dropTable('users');
};

Run Migrations

In knexfile.js update with your config settings:

module.exports = {
  development: {
    client: 'mysql',
    connection: {
      host: '127.0.0.1',
      user: 'root',
      password: 'root',
      database: 'test',
    },
  },
}

then we run the following command from the terminal

  $ npx knex migrate:latest 

Create Seeds

  $ npx knex seed:make [name_seed]

Example file seeds

exports.seed = function (knex) {
  return knex('users')
    .del()
    .then(function () {
      return knex('users').insert([
        { id: 1, firstName: 'firstName#1', lastName: 'lastName#1' },
        { id: 2, firstName: 'firstName#2', lastName: 'lastName#2' },
        { id: 3, firstName: 'firstName#3', lastName: 'lastName#3' },
      ]);
    });
};

Run Seeds

  $ npx knex seed:run 

For more information on Knex.js see here

Contribute

Feel free to help this library, I'm quite busy with also another Nestjs packages, but the community will appreciate the effort of improving this library. Make sure you follow the guidelines

Stay in touch

License

MIT licensed