/nestjs-knex-demo

nest.js 使用 knex.js 作为数据库交互工具的 demo

Primary LanguageTypeScript

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

Overview

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { KnexModule } from './modules/common/knex/knex.module';

@Module({
  imports: [
    KnexModule.forRoot({
      client: 'mysql',
      connection: {
        host: '127.0.0.1',
        user: 'blog',
        password: '123456',
        database: 'blog',
      },
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

app.serverce.ts

import { Injectable, Inject } from '@nestjs/common';
import { Knex } from 'knex';
import { KNEX_CONNECTION } from './modules/common/knex/constants';

@Injectable()
export class AppService {
  constructor(@Inject(KNEX_CONNECTION) private readonly knex: Knex) { }

  async getHello(): Promise<any> {
    // use knex
    return await this.knex('article').select()
  }
}

Installation

$ npm install

Running the app

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Test

# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov

Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.

Stay in touch

License

Nest is MIT licensed.