nestjs-telegraf/lib/telegraf-update.explorer.ts

64 lines
2.0 KiB
TypeScript
Raw Normal View History

import { Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { DiscoveryService } from '@nestjs/core';
2020-03-19 16:21:35 +03:00
import { MetadataScanner } from '@nestjs/core/metadata-scanner';
import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper';
import { Telegraf } from 'telegraf';
2020-12-26 16:11:09 +03:00
import { TelegrafMetadataAccessor } from './telegraf.metadata-accessor';
2020-03-19 16:21:35 +03:00
@Injectable()
export class TelegrafUpdateExplorer implements OnModuleInit {
2020-03-19 16:21:35 +03:00
constructor(
@Inject(Telegraf)
private readonly telegraf: Telegraf,
2020-03-19 16:21:35 +03:00
private readonly discoveryService: DiscoveryService,
private readonly metadataAccessor: TelegrafMetadataAccessor,
private readonly metadataScanner: MetadataScanner,
) {}
onModuleInit(): void {
2020-03-19 16:21:35 +03:00
this.explore();
}
private explore(): void {
const updateClasses = this.filterUpdateClasses();
2020-12-26 16:11:09 +03:00
2020-12-26 16:24:38 +03:00
updateClasses.forEach((wrapper) => {
2020-12-26 16:11:09 +03:00
const { instance } = wrapper;
2020-12-26 16:11:09 +03:00
const prototype = Object.getPrototypeOf(instance);
this.metadataScanner.scanFromPrototype(
instance,
prototype,
2020-12-26 16:24:38 +03:00
(methodKey: string) => this.registerIfListener(instance, methodKey),
2020-12-26 16:11:09 +03:00
);
});
}
private filterUpdateClasses(): InstanceWrapper[] {
2020-12-26 16:11:09 +03:00
return this.discoveryService
.getProviders()
.filter((wrapper) => wrapper.instance)
2020-12-26 16:24:38 +03:00
.filter((wrapper) =>
this.metadataAccessor.isUpdate(wrapper.instance.constructor),
);
}
2020-12-26 16:24:38 +03:00
private registerIfListener(
instance: Record<string, Function>,
methodKey: string,
): void {
const methodRef = instance[methodKey];
const middlewareFn = methodRef.bind(instance);
const listenerMetadata = this.metadataAccessor.getListenerMetadata(
methodRef,
);
if (!listenerMetadata) return;
const { method, args } = listenerMetadata;
// NOTE: Use "any" to disable "Expected at least 1 arguments, but got 1 or more." error.
// Use telegraf instance for non-scene listeners
(this.telegraf[method] as any)(...args, middlewareFn);
}
2020-03-19 16:21:35 +03:00
}