feat(decorators): TelegrafCommand added

This commit is contained in:
Aleksandr Bukhalo 2020-03-19 16:39:47 +03:00
parent 6fddfd26f0
commit c0ffdeff34
5 changed files with 39 additions and 0 deletions

View File

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

View File

@ -0,0 +1,12 @@
import { SetMetadata } from '@nestjs/common';
import { DECORATORS } from '../telegraf.constants';
/**
* Command handling.
* @param commands Commands
*
* https://telegraf.js.org/#/?id=command
*/
export function TelegrafCommand(commands: string | string[]): MethodDecorator {
return SetMetadata(DECORATORS.COMMAND, { commands });
}

View File

@ -42,4 +42,15 @@ export class TelegrafMetadataAccessor {
getTelegrafHearsMetadata(target: Type<any> | Function) {
return this.reflector.get(DECORATORS.HEARS, target);
}
isTelegrafCommand(target: Type<any> | Function): boolean {
if (!target) {
return false;
}
return !!this.reflector.get(DECORATORS.COMMAND, target);
}
getTelegrafCommandMetadata(target: Type<any> | Function) {
return this.reflector.get(DECORATORS.COMMAND, target);
}
}

View File

@ -6,5 +6,6 @@ export const DECORATORS = {
USE: `${DECORATORS_PREFIX}/USE`,
ON: `${DECORATORS_PREFIX}/ON`,
HEARS: `${DECORATORS_PREFIX}/HEARS`,
COMMAND: `${DECORATORS_PREFIX}/COMMAND`,
START: `${DECORATORS_PREFIX}/START`,
};

View File

@ -53,6 +53,11 @@ export class TelegrafExplorer implements OnModuleInit {
instance[key],
);
this.handleTelegrafHears(instance, key, telegraf, metadata);
} else if (this.metadataAccessor.isTelegrafCommand(instance[key])) {
const metadata = this.metadataAccessor.getTelegrafCommandMetadata(
instance[key],
);
this.handleTelegrafCommand(instance, key, telegraf, metadata);
}
},
);
@ -92,4 +97,13 @@ export class TelegrafExplorer implements OnModuleInit {
) {
telegraf.hears(metadata.triggers, instance[key].bind(instance));
}
handleTelegrafCommand(
instance: object,
key: string,
telegraf: Telegraf<ContextMessageUpdate>,
metadata: any,
) {
telegraf.command(metadata.commands, instance[key].bind(instance));
}
}