nestjs-telegraf/lib/telegraf.module.ts

107 lines
2.8 KiB
TypeScript
Raw Normal View History

import { DiscoveryModule, ModuleRef } from '@nestjs/core';
import {
DynamicModule,
Inject,
Module,
OnApplicationBootstrap,
OnApplicationShutdown,
Provider,
} from '@nestjs/common';
import { Telegraf } from 'telegraf';
import {
TelegrafModuleAsyncOptions,
TelegrafModuleOptions,
TelegrafOptionsFactory,
} from './interfaces';
import { TELEGRAF_MODULE_OPTIONS } from './telegraf.constants';
2020-12-26 16:11:09 +03:00
import { TelegrafMetadataAccessor } from './telegraf.metadata-accessor';
import { TelegrafUpdateExplorer } from './telegraf-update.explorer';
import { TelegrafSceneExplorer } from './telegraf-scene.explorer';
import { createProviders, TelegrafProvider } from './telegraf.providers';
2019-02-28 11:29:26 +03:00
@Module({
imports: [DiscoveryModule],
providers: [
TelegrafMetadataAccessor,
TelegrafSceneExplorer,
TelegrafUpdateExplorer,
],
})
export class TelegrafModule
implements OnApplicationBootstrap, OnApplicationShutdown {
constructor(
@Inject(TELEGRAF_MODULE_OPTIONS)
private readonly options: TelegrafModuleOptions,
private readonly moduleRef: ModuleRef,
) {}
async onApplicationBootstrap(): Promise<void> {
const { launchOptions } = this.options;
const telegraf = this.moduleRef.get(Telegraf);
await telegraf.launch(launchOptions);
}
async onApplicationShutdown(): Promise<void> {
const telegraf = this.moduleRef.get(Telegraf);
await telegraf.stop();
}
2020-05-03 11:06:25 +03:00
public static forRoot(options: TelegrafModuleOptions): DynamicModule {
const providers = [...createProviders(options), TelegrafProvider];
2019-02-28 11:29:26 +03:00
return {
2020-01-12 01:15:32 +03:00
module: TelegrafModule,
providers,
exports: providers,
};
2019-02-28 11:29:26 +03:00
}
2020-03-19 16:21:35 +03:00
public static forRootAsync(
options: TelegrafModuleAsyncOptions,
): DynamicModule {
const providers = [...this.createAsyncProviders(options), TelegrafProvider];
return {
2020-03-19 16:21:35 +03:00
module: TelegrafModule,
imports: options.imports || [],
providers,
exports: providers,
};
}
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
}