feat: TelegrafUse decorator added

This commit is contained in:
Aleksandr Bukhalo 2020-03-19 16:34:44 +03:00
parent 9fedcb964f
commit 6fddfd26f0
5 changed files with 31 additions and 1 deletions

View File

@ -1,3 +1,4 @@
export * from './telegraf-use.decorator';
export * from './telegraf-on.decorator';
export * from './telegraf-hears.decorator';
export * from './telegraf-start.decorator';

View File

@ -0,0 +1,11 @@
import { SetMetadata } from '@nestjs/common';
import { DECORATORS } from '../telegraf.constants';
/**
* Registers a middleware.
*
* https://telegraf.js.org/#/?id=use
*/
export function TelegrafUse(): MethodDecorator {
return SetMetadata(DECORATORS.USE, {});
}

View File

@ -7,6 +7,13 @@ import { DECORATORS } from './telegraf.constants';
export class TelegrafMetadataAccessor {
constructor(private readonly reflector: Reflector) {}
isTelegrafUse(target: Type<any> | Function): boolean {
if (!target) {
return false;
}
return !!this.reflector.get(DECORATORS.USE, target);
}
isTelegrafStart(target: Type<any> | Function): boolean {
if (!target) {
return false;

View File

@ -3,6 +3,7 @@ export const TELEGRAF_PROVIDER = 'TELEGRAF_PROVIDER';
export const DECORATORS_PREFIX = 'TELEGRAF';
export const DECORATORS = {
USE: `${DECORATORS_PREFIX}/USE`,
ON: `${DECORATORS_PREFIX}/ON`,
HEARS: `${DECORATORS_PREFIX}/HEARS`,
START: `${DECORATORS_PREFIX}/START`,

View File

@ -39,7 +39,9 @@ export class TelegrafExplorer implements OnModuleInit {
instance,
Object.getPrototypeOf(instance),
(key: string) => {
if (this.metadataAccessor.isTelegrafStart(instance[key])) {
if (this.metadataAccessor.isTelegrafUse(instance[key])) {
this.handleTelegrafUse(instance, key, telegraf);
} else if (this.metadataAccessor.isTelegrafStart(instance[key])) {
this.handleTelegrafStart(instance, key, telegraf);
} else if (this.metadataAccessor.isTelegrafOn(instance[key])) {
const metadata = this.metadataAccessor.getTelegrafOnMetadata(
@ -57,6 +59,14 @@ export class TelegrafExplorer implements OnModuleInit {
});
}
handleTelegrafUse(
instance: object,
key: string,
telegraf: Telegraf<ContextMessageUpdate>,
) {
telegraf.use(instance[key].bind(instance));
}
handleTelegrafOn(
instance: object,
key: string,