feat: add GlobalUpdate decorator (#2)

This commit is contained in:
2023-07-23 15:38:05 +03:00
committed by GitHub
parent 7f43458c55
commit dca35a0c7f
5 changed files with 44 additions and 2 deletions

View File

@@ -48,8 +48,6 @@ export class ListenersExplorerService
this.bot = this.moduleRef.get<Telegraf<any>>(this.botName, {
strict: false,
});
this.bot.use(this.stage.middleware());
this.explore();
}
@@ -59,10 +57,23 @@ export class ListenersExplorerService
this.telegrafOptions.include || [],
);
this.registerGlobalUpdates(modules);
this.bot.use(this.stage.middleware());
this.registerUpdates(modules);
this.registerScenes(modules);
}
private registerGlobalUpdates(modules: Module[]): void {
const globalUpdates = this.flatMap<InstanceWrapper>(modules, (instance) =>
this.filterGlobalUpdates(instance),
);
globalUpdates.forEach((wrapper) =>
this.registerListeners(this.bot, wrapper),
);
}
private registerUpdates(modules: Module[]): void {
const updates = this.flatMap<InstanceWrapper>(modules, (instance) =>
this.filterUpdates(instance),
@@ -92,6 +103,20 @@ export class ListenersExplorerService
});
}
private filterGlobalUpdates(
wrapper: InstanceWrapper,
): InstanceWrapper<unknown> {
const { instance } = wrapper;
if (!instance) return undefined;
const isGlobalUpdate = this.metadataAccessor.isGlobalUpdate(
wrapper.metatype,
);
if (!isGlobalUpdate) return undefined;
return wrapper;
}
private filterUpdates(wrapper: InstanceWrapper): InstanceWrapper<unknown> {
const { instance } = wrapper;
if (!instance) return undefined;

View File

@@ -3,6 +3,7 @@ import { Reflector } from '@nestjs/core';
import {
SCENE_METADATA,
LISTENERS_METADATA,
GLOBAL_UPDATE_METADATA,
UPDATE_METADATA,
WIZARD_STEP_METADATA,
} from '../telegraf.constants';
@@ -16,6 +17,11 @@ import {
export class MetadataAccessorService {
constructor(private readonly reflector: Reflector) {}
isGlobalUpdate(target: Function): boolean {
if (!target) return false;
return !!this.reflector.get(GLOBAL_UPDATE_METADATA, target);
}
isUpdate(target: Function): boolean {
if (!target) return false;
return !!this.reflector.get(UPDATE_METADATA, target);