feat(decorators): TelegrafEntity added

This commit is contained in:
Aleksandr Bukhalo 2020-03-19 16:54:34 +03:00
parent 55c6f939a4
commit 8bd20131a1
5 changed files with 42 additions and 0 deletions

View File

@ -4,3 +4,4 @@ export * from './telegraf-hears.decorator';
export * from './telegraf-command.decorator';
export * from './telegraf-start.decorator';
export * from './telegraf-help.decorator';
export * from './telegraf-entity.decorator';

View File

@ -0,0 +1,14 @@
import { SetMetadata } from '@nestjs/common';
import { DECORATORS } from '../telegraf.constants';
export type Entity = string | string[] | RegExp | RegExp[] | Function;
/**
* Entity handling.
* @param entity Entity name
*
* https://telegraf.js.org/#/?id=entity
*/
export function TelegrafEntity(entity: Entity): MethodDecorator {
return SetMetadata(DECORATORS.ENTITY, { entity });
}

View File

@ -67,4 +67,15 @@ export class TelegrafMetadataAccessor {
}
return !!this.reflector.get(DECORATORS.SETTINGS, target);
}
isTelegrafEntity(target: Type<any> | Function): boolean {
if (!target) {
return false;
}
return !!this.reflector.get(DECORATORS.ENTITY, target);
}
getTelegrafEntityMetadata(target: Type<any> | Function) {
return this.reflector.get(DECORATORS.ENTITY, target);
}
}

View File

@ -10,4 +10,5 @@ export const DECORATORS = {
START: `${DECORATORS_PREFIX}/START`,
HELP: `${DECORATORS_PREFIX}/HELP`,
SETTINGS: `${DECORATORS_PREFIX}/SETTINGS`,
ENTITY: `${DECORATORS_PREFIX}/ENTITY`,
};

View File

@ -62,6 +62,11 @@ export class TelegrafExplorer implements OnModuleInit {
this.handleTelegrafHelp(instance, key, telegraf);
} else if (this.metadataAccessor.isTelegrafSettings(instance[key])) {
this.handleTelegrafSettings(instance, key, telegraf);
} else if (this.metadataAccessor.isTelegrafEntity(instance[key])) {
const metadata = this.metadataAccessor.getTelegrafEntityMetadata(
instance[key],
);
this.handleTelegrafEntity(instance, key, telegraf, metadata);
}
},
);
@ -127,4 +132,14 @@ export class TelegrafExplorer implements OnModuleInit {
// @ts-ignore
telegraf.settings(instance[key].bind(instance));
}
handleTelegrafEntity(
instance: object,
key: string,
telegraf: Telegraf<ContextMessageUpdate>,
metadata: any,
) {
// @ts-ignore
telegraf.entity(metadata.entity, instance[key].bind(instance));
}
}