Skip to content

Commit

Permalink
feat: add onStop hook
Browse files Browse the repository at this point in the history
  • Loading branch information
kravetsone committed Mar 29, 2024
1 parent c83b940 commit c7c0f01
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "gramio",
"version": "0.0.23",
"version": "0.0.24",
"description": "Powerful Telegram Bot API framework",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand Down
19 changes: 16 additions & 3 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export class Bot<
preRequest: [],
onError: [],
onStart: [],
onStop: [],
};

constructor(token: string, options?: Omit<BotOptions, "token">) {
Expand Down Expand Up @@ -103,7 +104,10 @@ export class Bot<
}

private async runHooks<
T extends Exclude<keyof Hooks.Store<Errors>, "onError" | "onStart">,
T extends Exclude<
keyof Hooks.Store<Errors>,
"onError" | "onStart" | "onStop"
>,
>(type: T, context: Parameters<Hooks.Store<Errors>[T][0]>[0]) {
let data = context;

Expand All @@ -115,7 +119,10 @@ export class Bot<
}

private async runImmutableHooks<
T extends Extract<keyof Hooks.Store<Errors>, "onError" | "onStart">,
T extends Extract<
keyof Hooks.Store<Errors>,
"onError" | "onStart" | "onStop"
>,
>(type: T, context: Parameters<Hooks.Store<Errors>[T][0]>[0]) {
for await (const hook of this.hooks[type]) {
//TODO: solve that later
Expand Down Expand Up @@ -606,9 +613,15 @@ export class Bot<

return this.info;
}

/** Currently does not implement graceful shutdown */
async stop() {
if (this.updates.isStarted) this.updates.stopPolling();
else await this.api.deleteWebhook();

await this.runImmutableHooks("onStop", {
plugins: this.dependencies,
// biome-ignore lint/style/noNonNullAssertion: bot.init() guarantees this.info
info: this.info!,
});
}
}
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,16 @@ export namespace Hooks {
updatesFrom: "webhook" | "long-polling";
}) => unknown;

export type OnStop = (context: {
plugins: string[];
info: TelegramUser;
}) => unknown;

export interface Store<T extends ErrorDefinitions> {
preRequest: PreRequest[];
onError: OnError<T>[];
onStart: OnStart[];
onStop: OnStop[];
}
}

Expand Down

0 comments on commit c7c0f01

Please sign in to comment.