import { Global , Module , DynamicModule , Provider } from '@nestjs/common' ; import { KnexModuleAsyncOptions , KnexModuleOptions , KnexModuleOptionsFactory , } from './knex.interfaces' ; import { createKnexConnection , getKnexOptionsToken , getKnexConnectionToken , } from './knex.utils' ; @ Global ( ) @ Module ( { } ) export class KnexCoreModule { static forRoot ( options , connection ? ) { const knexOptionsProvider = { provide : getKnexOptionsToken ( connection ) , useValue : options , } ; const knexConnectionProvider = { provide : getKnexConnectionToken ( connection ) , useValue : createKnexConnection ( options ) , } ; return { module : KnexCoreModule , providers : [ knexOptionsProvider , knexConnectionProvider ] , exports : [ knexOptionsProvider , knexConnectionProvider ] , } ; } public static forRootAsync ( options , connection ) { const knexConnectionProvider = { provide : getKnexConnectionToken ( connection ) , useFactory ( options ) { return createKnexConnection ( options ) ; } , inject : [ getKnexOptionsToken ( connection ) ] , } ; return { module : KnexCoreModule , imports : options . imports , providers : [ ... this . createAsyncProviders ( options , connection ) , knexConnectionProvider , ] , exports : [ knexConnectionProvider ] , } ; } public static createAsyncProviders ( options , connection ? ) { if ( ! ( options . useExisting || options . useFactory || options . useClass ) ) { throw new Error ( 'Invalid configuration. Must provide useFactory, useClass or useExisting' ) ; } if ( options . useExisting || options . useFactory ) { return [ this . createAsyncOptionsProvider ( options , connection ) ] ; } return [ this . createAsyncOptionsProvider ( options , connection ) , { provide : options . useClass , useClass : options . useClass } , ] ; } public static createAsyncOptionsProvider ( options , connection ? ) { if ( ! ( options . useExisting || options . useFactory || options . useClass ) ) { throw new Error ( 'Invalid configuration. Must provide useFactory, useClass or useExisting' ) ; } if ( options . useFactory ) { return { provide : getKnexOptionsToken ( connection ) , useFactory : options . useFactory , inject : options . inject || [ ] , } ; } return { provide : getKnexOptionsToken ( connection ) , async useFactory ( optionsFactory ) { return optionsFactory . createKnexModuleOptions ( ) ; } , inject : [ options . useClass || options . useExisting ] , } ; } }