diff --git a/lib/decorators/index.ts b/lib/decorators/index.ts index d001649..42c00a1 100644 --- a/lib/decorators/index.ts +++ b/lib/decorators/index.ts @@ -1,3 +1,4 @@ +export * from './telegraf-use.decorator'; export * from './telegraf-on.decorator'; export * from './telegraf-hears.decorator'; export * from './telegraf-start.decorator'; diff --git a/lib/decorators/telegraf-use.decorator.ts b/lib/decorators/telegraf-use.decorator.ts new file mode 100644 index 0000000..2ff0dd7 --- /dev/null +++ b/lib/decorators/telegraf-use.decorator.ts @@ -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, {}); +} diff --git a/lib/telegraf-metadata.accessor.ts b/lib/telegraf-metadata.accessor.ts index d4bc776..cad0d9b 100644 --- a/lib/telegraf-metadata.accessor.ts +++ b/lib/telegraf-metadata.accessor.ts @@ -7,6 +7,13 @@ import { DECORATORS } from './telegraf.constants'; export class TelegrafMetadataAccessor { constructor(private readonly reflector: Reflector) {} + isTelegrafUse(target: Type | Function): boolean { + if (!target) { + return false; + } + return !!this.reflector.get(DECORATORS.USE, target); + } + isTelegrafStart(target: Type | Function): boolean { if (!target) { return false; diff --git a/lib/telegraf.constants.ts b/lib/telegraf.constants.ts index edfedfd..d68f1aa 100644 --- a/lib/telegraf.constants.ts +++ b/lib/telegraf.constants.ts @@ -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`, diff --git a/lib/telegraf.explorer.ts b/lib/telegraf.explorer.ts index ebe0405..feda0f0 100644 --- a/lib/telegraf.explorer.ts +++ b/lib/telegraf.explorer.ts @@ -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, + ) { + telegraf.use(instance[key].bind(instance)); + } + handleTelegrafOn( instance: object, key: string,