Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(webhook): change the way to get webhook handler #743

Merged
merged 8 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 9 additions & 13 deletions src/convenience/frameworks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,8 @@ export type HonoAdapter = (c: {
json: <T>() => Promise<T>;
header: (header: string) => string | undefined;
};
body: (
data: string | ArrayBuffer | ReadableStream | null,
// deno-lint-ignore no-explicit-any
arg?: any,
headers?: Record<string, string | string[]>,
) => Response;
body(data: string): Response;
body(data: null, status: 204): Response;
// deno-lint-ignore no-explicit-any
status: (status: any) => void;
json: (json: string) => Response;
Expand Down Expand Up @@ -390,14 +386,14 @@ const hono: HonoAdapter = (c) => {
update: c.req.json(),
header: c.req.header(SECRET_HEADER),
end: () => {
resolveResponse(c.body(null));
resolveResponse(c.body(""));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this change?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just copy hono part from main branch to fix broken test

},
respond: (json) => {
resolveResponse(c.json(json));
},
unauthorized: () => {
c.status(401);
resolveResponse(c.body(null));
resolveResponse(c.body(""));
},
handlerReturn: new Promise<Response>((resolve) => {
resolveResponse = resolve;
Expand Down Expand Up @@ -545,23 +541,23 @@ const worktop: WorktopAdapter = (req, res) => ({

// Please open a pull request if you want to add another adapter
export const adapters = {
"aws-lambda": awsLambda,
"aws-lambda-async": awsLambdaAsync,
awsLambda,
awsLambdaAsync,
azure,
bun,
cloudflare,
"cloudflare-mod": cloudflareModule,
cloudflareModule,
express,
fastify,
hono,
http,
https: http,
koa,
"next-js": nextJs,
nextJs,
nhttp,
oak,
serveHttp,
"std/http": stdHttp,
stdHttp,
sveltekit,
worktop,
};
182 changes: 137 additions & 45 deletions src/convenience/webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const adapters = { ...nativeAdapters, callback: callbackAdapter };

export interface WebhookOptions {
/** An optional strategy to handle timeouts (default: 'throw') */
onTimeout?: "throw" | "return" | ((...args: any[]) => unknown);
onTimeout?: "throw" | "ignore" | ((...args: any[]) => unknown);
/** An optional number of timeout milliseconds (default: 10_000) */
timeoutMilliseconds?: number;
/** An optional string to compare to X-Telegram-Bot-Api-Secret-Token */
Expand All @@ -34,8 +34,129 @@ export interface WebhookOptions {

type Adapters = typeof adapters;
type AdapterNames = keyof Adapters;
type ResolveName<A extends FrameworkAdapter | AdapterNames> = A extends
AdapterNames ? Adapters[A] : A;
type Adapter<A extends Adapters[AdapterNames]> = (
...args: Parameters<A>
) => ReturnType<A>["handlerReturn"] extends undefined ? Promise<void>
: NonNullable<ReturnType<A>["handlerReturn"]>;
type WebhookAdapter<
C extends Context = Context,
A extends Adapters[AdapterNames] = Adapters[AdapterNames],
> = {
(
bot: Bot<C>,
webhookOptions?: WebhookOptions,
): Adapter<A>;
(
bot: Bot<C>,
onTimeout?: WebhookOptions["onTimeout"],
timeoutMilliseconds?: WebhookOptions["timeoutMilliseconds"],
secretToken?: WebhookOptions["secretToken"],
): Adapter<A>;
};

function createWebhookAdapter<
C extends Context = Context,
A extends Adapters[AdapterNames] = Adapters[AdapterNames],
>(adapter: A): WebhookAdapter<C, A> {
return (
bot: Bot<C>,
onTimeout?:
| WebhookOptions
| WebhookOptions["onTimeout"],
timeoutMilliseconds?: WebhookOptions["timeoutMilliseconds"],
secretToken?: WebhookOptions["secretToken"],
) => {
const {
onTimeout: timeout = "throw",
timeoutMilliseconds: ms = 10_000,
secretToken: token,
} = typeof onTimeout === "object"
? onTimeout
: { onTimeout, timeoutMilliseconds, secretToken };

return webhookCallback(bot, adapter, timeout, ms, token);
};
}
// TODO: add docs examples for each adapter?
/**
* Contains factories of callback function that you can pass to a web framework
* (such as express) if you want to run your bot via webhooks. Use it like this:
* ```ts
* const app = express() // or whatever you're using
* const bot = new Bot('<token>')
*
* app.use(webhookAdapters.express(bot))
* ```
*
* Confer the grammY
* [documentation](https://grammy.dev/guide/deployment-types) to read more
* about how to run your bot with webhooks.
*
* @param bot The bot for which to create a callback
* @param webhookOptions Further options for the webhook setup
*/
export const webhookAdapters = {
get awsLambda() {
return createWebhookAdapter(adapters.awsLambda);
},
get awsLambdaAsync() {
return createWebhookAdapter(adapters.awsLambdaAsync);
},
get azure() {
return createWebhookAdapter(adapters.azure);
},
get bun() {
return createWebhookAdapter(adapters.bun);
},
get cloudflare() {
return createWebhookAdapter(adapters.cloudflare);
},
get cloudflareModule() {
return createWebhookAdapter(adapters.cloudflareModule);
},
get express() {
return createWebhookAdapter(adapters.express);
},
get fastify() {
return createWebhookAdapter(adapters.fastify);
},
get hono() {
return createWebhookAdapter(adapters.hono);
},
get http() {
return createWebhookAdapter(adapters.http);
},
get https() {
return createWebhookAdapter(adapters.http);
},
get koa() {
return createWebhookAdapter(adapters.koa);
},
get nextJs() {
return createWebhookAdapter(adapters.nextJs);
},
get nhttp() {
return createWebhookAdapter(adapters.nhttp);
},
get oak() {
return createWebhookAdapter(adapters.oak);
},
get serveHttp() {
return createWebhookAdapter(adapters.serveHttp);
},
get stdHttp() {
return createWebhookAdapter(adapters.stdHttp);
},
get sveltekit() {
return createWebhookAdapter(adapters.sveltekit);
},
get worktop() {
return createWebhookAdapter(adapters.worktop);
},
get callback() {
return createWebhookAdapter(adapters.callback);
},
};

/**
* Creates a callback function that you can pass to a web framework (such as
Expand All @@ -55,39 +176,14 @@ type ResolveName<A extends FrameworkAdapter | AdapterNames> = A extends
* @param adapter An optional string identifying the framework (default: 'express')
* @param webhookOptions Further options for the webhook setup
*/
export function webhookCallback<
C extends Context = Context,
A extends FrameworkAdapter | AdapterNames = FrameworkAdapter | AdapterNames,
>(
bot: Bot<C>,
adapter: A,
webhookOptions?: WebhookOptions,
): (
...args: Parameters<ResolveName<A>>
) => ReturnType<ResolveName<A>>["handlerReturn"] extends undefined
? Promise<void>
: NonNullable<ReturnType<ResolveName<A>>["handlerReturn"]>;
export function webhookCallback<
C extends Context = Context,
A extends FrameworkAdapter | AdapterNames = FrameworkAdapter | AdapterNames,
>(
bot: Bot<C>,
adapter: A,
onTimeout?: WebhookOptions["onTimeout"],
timeoutMilliseconds?: WebhookOptions["timeoutMilliseconds"],
secretToken?: WebhookOptions["secretToken"],
): (
...args: Parameters<ResolveName<A>>
) => ReturnType<ResolveName<A>>["handlerReturn"] extends undefined
? Promise<void>
: NonNullable<ReturnType<ResolveName<A>>["handlerReturn"]>;
export function webhookCallback<C extends Context = Context>(
function webhookCallback<C extends Context = Context>(
bot: Bot<C>,
adapter: FrameworkAdapter | AdapterNames,
onTimeout?:
| WebhookOptions
| WebhookOptions["onTimeout"],
timeoutMilliseconds?: WebhookOptions["timeoutMilliseconds"],
onTimeout: Exclude<WebhookOptions["onTimeout"], undefined>,
timeoutMilliseconds: Exclude<
WebhookOptions["timeoutMilliseconds"],
undefined
>,
secretToken?: WebhookOptions["secretToken"],
) {
if (bot.isRunning()) {
Expand All @@ -101,13 +197,7 @@ export function webhookCallback<C extends Context = Context>(
);
};
}
const {
onTimeout: timeout = "throw",
timeoutMilliseconds: ms = 10_000,
secretToken: token,
} = typeof onTimeout === "object"
? onTimeout
: { onTimeout, timeoutMilliseconds, secretToken };

let initialized = false;
const server: FrameworkAdapter = typeof adapter === "string"
? adapters[adapter]
Expand All @@ -120,7 +210,7 @@ export function webhookCallback<C extends Context = Context>(
await bot.init();
initialized = true;
}
if (header !== token) {
if (header !== secretToken) {
await unauthorized();
// TODO: investigate deno bug that happens when this console logging is removed
console.log(handlerReturn);
Expand All @@ -135,8 +225,10 @@ export function webhookCallback<C extends Context = Context>(
};
await timeoutIfNecessary(
bot.handleUpdate(await update, webhookReplyEnvelope),
typeof timeout === "function" ? () => timeout(...args) : timeout,
ms,
typeof onTimeout === "function"
? () => onTimeout(...args)
: onTimeout,
timeoutMilliseconds,
);
if (!usedWebhookReply) end?.();
return handlerReturn;
Expand All @@ -145,7 +237,7 @@ export function webhookCallback<C extends Context = Context>(

function timeoutIfNecessary(
task: Promise<void>,
onTimeout: "throw" | "return" | (() => unknown),
onTimeout: "throw" | "ignore" | (() => unknown),
timeout: number,
): Promise<void> {
if (timeout === Infinity) return task;
Expand Down
Loading