From 22739f4bd7879ab28a6791c02186bcc2e687d748 Mon Sep 17 00:00:00 2001 From: Kravets <57632712+kravetsone@users.noreply.github.com> Date: Thu, 4 Jul 2024 00:44:39 +0300 Subject: [PATCH] feat: add `decorate` feature --- src/bot.ts | 22 ++++++++++++++++++++++ src/plugin.ts | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/bot.ts b/src/bot.ts index 4fb1987..671fad3 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -8,6 +8,7 @@ import { type MaybeArray, PhotoAttachment, type UpdateName, + contextsMappings, } from "@gramio/contexts"; import { convertJsonToFormData, isMediaUpload } from "@gramio/files"; import { FormattableMap } from "@gramio/format"; @@ -464,6 +465,23 @@ export class Bot< return this; } + decorate(name: Name, value: Value) { + for (const contextName of Object.keys(contextsMappings)) { + // @ts-expect-error + Object.defineProperty(contextsMappings[contextName].prototype, name, { + value, + }); + } + + return this as unknown as Bot< + Errors, + Derives & { + global: { + [K in Name]: Value; + }; + } + >; + } /** * This hook called when the bot is `started`. * @@ -737,6 +755,10 @@ export class Bot< this.use(plugin._.composer.composed); } + for (const [key, value] of Object.entries(plugin._.decorators)) { + this.decorate(key, value); + } + for (const [key, value] of Object.entries(plugin._.errorsDefinitions)) { if (this.errorsDefinitions[key]) this.errorsDefinitions[key] = value; } diff --git a/src/plugin.ts b/src/plugin.ts index d158e85..2cba67d 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -108,6 +108,7 @@ export class Plugin< string, { new (...args: any): any; prototype: Error } >, + decorators: {} as Record, }; /** Create new Plugin. Please provide `name` */ @@ -181,6 +182,19 @@ export class Plugin< return this; } + decorate(name: Name, value: Value) { + this._.decorators[name] = value; + + return this as unknown as Plugin< + Errors, + Derives & { + global: { + [K in Name]: Value; + }; + } + >; + } + /** Register handler to one or many Updates */ on( updateName: MaybeArray,