项目作者: svtslv

项目描述 :
Knex module for Nest
高级语言: TypeScript
项目地址: git://github.com/svtslv/nestjs-knex.git
创建时间: 2020-02-28T20:05:04Z
项目社区:https://github.com/svtslv/nestjs-knex

开源协议:

下载


NestJS Knex

NPM Version
Package License

Table of Contents

Description

Integrates Knex with Nest

Installation

  1. npm install nestjs-knex knex

You can also use the interactive CLI

  1. npx nestjs-modules

Examples

  1. npm install nestjs-knex knex sqlite3

KnexModule.forRoot(options, connection?)

  1. import { Module } from '@nestjs/common';
  2. import { KnexModule } from 'nestjs-knex';
  3. import { AppController } from './app.controller';
  4. @Module({
  5. imports: [
  6. KnexModule.forRoot({
  7. config: {
  8. client: "sqlite3",
  9. useNullAsDefault: true,
  10. connection: ':memory:',
  11. },
  12. }),
  13. ],
  14. controllers: [AppController],
  15. })
  16. export class AppModule {}

KnexModule.forRootAsync(options, connection?)

  1. import { Module } from '@nestjs/common';
  2. import { KnexModule } from 'nestjs-knex';
  3. import { AppController } from './app.controller';
  4. @Module({
  5. imports: [
  6. KnexModule.forRootAsync({
  7. useFactory: () => ({
  8. config: {
  9. client: "sqlite3",
  10. useNullAsDefault: true,
  11. connection: ':memory:',
  12. },
  13. }),
  14. }),
  15. ],
  16. controllers: [AppController],
  17. })
  18. export class AppModule {}

InjectKnex(connection?)

  1. import { Controller, Get, } from '@nestjs/common';
  2. import { InjectKnex, Knex } from 'nestjs-knex';
  3. @Controller()
  4. export class AppController {
  5. constructor(
  6. @InjectKnex() private readonly knex: Knex,
  7. ) {}
  8. @Get()
  9. async getHello() {
  10. if (!await this.knex.schema.hasTable('users')) {
  11. await this.knex.schema.createTable('users', table => {
  12. table.increments('id').primary();
  13. table.string('name');
  14. });
  15. }
  16. await this.knex.table('users').insert({ name: 'Name' });
  17. const users = await this.knex.table('users');
  18. return { users };
  19. }
  20. }

License

MIT