feat(listeners): support for chaining method listeners

This commit is contained in:
xTCry [Vladislav Kh]
2021-08-01 07:31:09 +03:00
parent 0339fe15ae
commit a4cb8df434
4 changed files with 41 additions and 28 deletions

View File

@@ -1,17 +1,29 @@
import { SetMetadata } from '@nestjs/common';
import { Composer } from 'telegraf';
import { ComposerMethodArgs, OnlyFunctionPropertyNames } from '../types';
import { LISTENER_METADATA } from '../telegraf.constants';
import { LISTENERS_METADATA } from '../telegraf.constants';
import { ListenerMetadata } from '../interfaces';
export function createListenerDecorator<
TComposer extends Composer<never>,
TMethod extends OnlyFunctionPropertyNames<TComposer> = OnlyFunctionPropertyNames<TComposer>
TMethod extends OnlyFunctionPropertyNames<TComposer> = OnlyFunctionPropertyNames<TComposer>,
>(method: TMethod) {
return (...args: ComposerMethodArgs<TComposer, TMethod>): MethodDecorator => {
return SetMetadata(LISTENER_METADATA, {
method,
args,
} as ListenerMetadata);
return (
_target: any,
_key?: string | symbol,
descriptor?: TypedPropertyDescriptor<any>,
) => {
const metadata = [
{
method,
args,
} as ListenerMetadata,
];
const previousValue = Reflect.getMetadata(LISTENERS_METADATA, descriptor.value) || [];
const value = [...previousValue, ...metadata];
Reflect.defineMetadata(LISTENERS_METADATA, value, descriptor.value);
return descriptor;
};
};
}