Skip to content

Commit

Permalink
feat: add decorate feature
Browse files Browse the repository at this point in the history
  • Loading branch information
kravetsone committed Jul 3, 2024
1 parent 1416091 commit 22739f4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -464,6 +465,23 @@ export class Bot<
return this;
}

decorate<Name extends string, Value>(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`.
*
Expand Down Expand Up @@ -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;
}
Expand Down
14 changes: 14 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export class Plugin<
string,
{ new (...args: any): any; prototype: Error }
>,
decorators: {} as Record<string, unknown>,
};

/** Create new Plugin. Please provide `name` */
Expand Down Expand Up @@ -181,6 +182,19 @@ export class Plugin<
return this;
}

decorate<Name extends string, Value>(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<T extends UpdateName>(
updateName: MaybeArray<T>,
Expand Down

0 comments on commit 22739f4

Please sign in to comment.