npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nest-knexjs

v0.0.24

Published

Knexjs module for Nest framework (node.js) 😻

Downloads

26,752

Readme

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