nestjs-telegraf/lib/telegraf.module.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-02-28 11:29:26 +03:00
import {
Module,
DynamicModule,
Provider,
2019-02-28 11:29:26 +03:00
} from '@nestjs/common'
import { TelegramBot } from './TelegramBot'
import {
TelegrafModuleAsyncOptions,
TelegrafOptionsFactory,
} from './interfaces'
import { TELEGRAF_MODULE_OPTIONS } from './telegraf.constants'
2019-02-28 11:29:26 +03:00
import { TokenInjectionToken } from './TokenInjectionToken'
import { TelegramClient } from './TelegramClient'
2019-02-28 11:29:26 +03:00
@Module({})
export class TelegrafModule {
static fromFactory(options: TelegrafModuleAsyncOptions): DynamicModule {
2019-02-28 11:29:26 +03:00
return {
2020-01-12 01:15:32 +03:00
module: TelegrafModule,
imports: options.imports || [],
2019-02-28 11:29:26 +03:00
providers: [
...this.createAsyncProviders(options),
2019-02-28 11:29:26 +03:00
TelegramBot,
TelegramClient,
2019-02-28 11:29:26 +03:00
{
provide: TokenInjectionToken,
useClass: options.useClass,
2019-02-28 11:29:26 +03:00
},
],
2019-05-11 21:10:14 +03:00
exports: [TelegramBot, TelegramClient],
2019-02-28 11:29:26 +03:00
}
}
private static createAsyncProviders(
options: TelegrafModuleAsyncOptions,
): Provider[] {
if (options.useExisting || options.useFactory) {
return [this.createAsyncOptionsProvider(options)]
}
return [
this.createAsyncOptionsProvider(options),
{
provide: options.useClass,
useClass: options.useClass,
},
]
}
private static createAsyncOptionsProvider(
options: TelegrafModuleAsyncOptions,
): Provider {
if (options.useFactory) {
return {
provide: TELEGRAF_MODULE_OPTIONS,
useFactory: options.useFactory,
inject: options.inject || [],
}
}
return {
provide: TELEGRAF_MODULE_OPTIONS,
useFactory: async (optionsFactory: TelegrafOptionsFactory) =>
await optionsFactory.createTelegrafOptions(),
inject: [options.useExisting || options.useClass],
}
}
2019-02-28 11:29:26 +03:00
}