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 5 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,
};
142 changes: 97 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,89 @@ 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 = {
awsLambda: createWebhookAdapter(adapters.awsLambda),
awsLambdaAsync: createWebhookAdapter(adapters.awsLambdaAsync),
azure: createWebhookAdapter(adapters.azure),
bun: createWebhookAdapter(adapters.bun),
cloudflare: createWebhookAdapter(adapters.cloudflare),
cloudflareModule: createWebhookAdapter(adapters.cloudflareModule),
express: createWebhookAdapter(adapters.express),
fastify: createWebhookAdapter(adapters.fastify),
hono: createWebhookAdapter(adapters.hono),
http: createWebhookAdapter(adapters.http),
https: createWebhookAdapter(adapters.http),
koa: createWebhookAdapter(adapters.koa),
nextJs: createWebhookAdapter(adapters.nextJs),
nhttp: createWebhookAdapter(adapters.nhttp),
oak: createWebhookAdapter(adapters.oak),
serveHttp: createWebhookAdapter(adapters.serveHttp),
stdHttp: createWebhookAdapter(adapters.stdHttp),
sveltekit: createWebhookAdapter(adapters.sveltekit),
worktop: createWebhookAdapter(adapters.worktop),
callback: createWebhookAdapter(adapters.callback),
};

/**
* Creates a callback function that you can pass to a web framework (such as
Expand All @@ -55,39 +136,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 +157,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 +170,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 +185,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 +197,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
30 changes: 15 additions & 15 deletions test/convenience/webhook.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type bodyParser from "npm:@types/koa-bodyparser";
import type Koa from "npm:@types/koa";
import type { FastifyInstance } from "npm:fastify";
import type { NextApiRequest, NextApiResponse } from "npm:next";
import { Bot, BotError, webhookCallback } from "../../src/mod.ts";
import { Bot, BotError, webhookAdapters } from "../../src/mod.ts";
import type { UserFromGetMe } from "../../src/types.ts";
import { assert, assertIsError, describe, it } from "../deps.test.ts";

Expand All @@ -20,7 +20,7 @@ describe("webhook", () => {

it("AWS Lambda should be compatible with grammY adapter", () => {
((event: APIGatewayProxyEventV2, context: LambdaContext) =>
webhookCallback(bot, "aws-lambda-async")(
webhookAdapters.awsLambdaAsync(bot)(
event,
context,
));
Expand All @@ -33,7 +33,7 @@ describe("webhook", () => {
},
) => object;

const handler = webhookCallback(bot, "bun");
const handler = webhookAdapters.bun(bot);
const serve = (() => {}) as unknown as BunServe;
serve({
fetch: (request) => {
Expand All @@ -47,37 +47,37 @@ describe("webhook", () => {
json: () => ({}),
headers: { get: () => "" },
} as unknown as Request;
const handler = webhookCallback(bot, "cloudflare-mod");
const handler = webhookAdapters.cloudflareModule(bot);
const _res: Response = await handler(req);
});

it("Express should be compatible with grammY adapter", () => {
const app = { post: () => {} } as unknown as Express;
const handler = webhookCallback(bot, "express");
const handler = webhookAdapters.express(bot);
app.post("/", (req, res) => {
return handler(req, res);
});
});

it("Fastify should be compatible with grammY adapter", () => {
const app = { post: () => {} } as unknown as FastifyInstance;
const handler = webhookCallback(bot, "fastify");
const handler = webhookAdapters.fastify(bot);
app.post("/", (request, reply) => {
return handler(request, reply);
});
});

it("Hono should be compatible with grammY adapter", () => {
const app = { post: () => {} } as unknown as Hono;
const handler = webhookCallback(bot, "hono");
const handler = webhookAdapters.hono(bot);
app.post("/", (c) => {
return handler(c);
});
});

it("http/https should be compatible with grammY adapter", () => {
const create = (() => {}) as unknown as typeof createServer;
const handler = webhookCallback(bot, "http");
const handler = webhookAdapters.http(bot);
create((req, res) => {
return handler(req, res);
});
Expand All @@ -86,7 +86,7 @@ describe("webhook", () => {
it("Koa should be compatible with grammY adapter", () => {
const app = { use: () => {} } as unknown as Koa;
const parser = (() => {}) as unknown as typeof bodyParser;
const handler = webhookCallback(bot, "koa");
const handler = webhookAdapters.koa(bot);
app.use(parser());
app.use((ctx) => {
return handler(ctx);
Expand All @@ -99,21 +99,21 @@ describe("webhook", () => {
body: { update: {} },
} as unknown as NextApiRequest;
const res = { end: () => {} } as NextApiResponse;
const handler = webhookCallback(bot, "next-js");
const handler = webhookAdapters.nextJs(bot);
await handler(req, res);
});

it("NHttp should be compatible with grammY adapter", () => {
const app = { post: () => {} } as unknown as NHttp;
const handler = webhookCallback(bot, "nhttp");
const handler = webhookAdapters.nhttp(bot);
app.post("/", (rev) => {
return handler(rev);
});
});

it("Oak should be compatible with grammY adapter", () => {
const app = { use: () => {} } as unknown as Application;
const handler = webhookCallback(bot, "oak");
const handler = webhookAdapters.oak(bot);
app.use((ctx) => {
return handler(ctx);
});
Expand All @@ -127,13 +127,13 @@ describe("webhook", () => {
}),
respondWith: () => {},
};
const handler = webhookCallback(bot, "serveHttp");
const handler = webhookAdapters.serveHttp(bot);
await handler(event);
});

it("std/http should be compatible with grammY adapter", () => {
const serve = (() => {}) as unknown as typeof Deno.serve;
const handler = webhookCallback(bot, "std/http");
const handler = webhookAdapters.stdHttp(bot);
serve((req) => {
return handler(req);
});
Expand All @@ -150,7 +150,7 @@ describe("webhook", () => {
throw new Error("Test Error");
});

const handler = webhookCallback(bot, "std/http");
const handler = webhookAdapters.stdHttp(bot);
const fakeReq = new Request("https://fake-api.com", {
method: "POST",
body: JSON.stringify({
Expand Down