refactor(): bot token using

This commit is contained in:
Morb0 2021-01-03 13:24:07 +03:00
parent d48123ea38
commit 5ada9353e9
4 changed files with 10 additions and 27 deletions

View File

@ -8,12 +8,12 @@ import {
export interface TelegrafModuleOptions<C extends Context = Context> {
token: string;
name?: string;
options?: TelegrafOptions;
launchOptions?: {
polling?: LaunchPollingOptions;
webhook?: LaunchWebhookOptions;
};
botName?: string;
include?: Function[];
middlewares?: ReadonlyArray<Middleware<C>>;
}

View File

@ -13,10 +13,7 @@ import {
TelegrafModuleAsyncOptions,
TelegrafOptionsFactory,
} from './interfaces';
import {
TELEGRAF_BOT_NAME,
TELEGRAF_MODULE_OPTIONS,
} from './telegraf.constants';
import { TELEGRAF_MODULE_OPTIONS } from './telegraf.constants';
import {
MetadataAccessorService,
ScenesExplorerService,
@ -36,15 +33,14 @@ import { createBotFactory } from './utils/create-bot-factory.util';
})
export class TelegrafCoreModule implements OnApplicationShutdown {
constructor(
@Inject(TELEGRAF_BOT_NAME) private readonly botName: string,
@Inject(TELEGRAF_MODULE_OPTIONS)
private readonly options: TelegrafModuleOptions,
private readonly moduleRef: ModuleRef,
) {}
public static forRoot(options: TelegrafModuleOptions): DynamicModule {
const telegrafBotName = getBotToken(options.botName);
const telegrafBotProvider: Provider = {
provide: telegrafBotName,
provide: getBotToken(options.name),
useFactory: async () => await createBotFactory(options),
};
@ -55,10 +51,6 @@ export class TelegrafCoreModule implements OnApplicationShutdown {
provide: TELEGRAF_MODULE_OPTIONS,
useValue: options,
},
{
provide: TELEGRAF_BOT_NAME,
useValue: telegrafBotName,
},
telegrafBotProvider,
],
exports: [telegrafBotProvider],
@ -81,20 +73,14 @@ export class TelegrafCoreModule implements OnApplicationShutdown {
return {
module: TelegrafCoreModule,
imports: options.imports,
providers: [
...asyncProviders,
{
provide: TELEGRAF_BOT_NAME,
useValue: telegrafBotName,
},
telegrafBotProvider,
],
providers: [...asyncProviders, telegrafBotProvider],
exports: [telegrafBotProvider],
};
}
async onApplicationShutdown(): Promise<void> {
const bot = this.moduleRef.get<any>(this.botName);
const botName = getBotToken(this.options.name);
const bot = this.moduleRef.get<any>(botName);
bot && (await bot.stop());
}

View File

@ -1,5 +1,4 @@
export const TELEGRAF_MODULE_OPTIONS = 'TELEGRAF_MODULE_OPTIONS';
export const TELEGRAF_BOT_NAME = 'TELEGRAF_BOT_NAME';
export const DEFAULT_BOT_NAME = 'DEFAULT_BOT_NAME';
export const UPDATE_METADATA = 'UPDATE_METADATA';

View File

@ -1,7 +1,5 @@
import { DEFAULT_BOT_NAME } from '../telegraf.constants';
export function getBotToken(name?: string) {
return name && name !== DEFAULT_BOT_NAME
? `${name}_BOT_NAME`
: DEFAULT_BOT_NAME;
export function getBotToken(name?: string): string {
return name && name !== DEFAULT_BOT_NAME ? `${name}Bot` : DEFAULT_BOT_NAME;
}