diff --git a/src/convenience/frameworks.ts b/src/convenience/frameworks.ts index ceec500d..4b0d0a04 100644 --- a/src/convenience/frameworks.ts +++ b/src/convenience/frameworks.ts @@ -15,48 +15,45 @@ const unauthorized = () => new Response(WRONG_TOKEN_ERROR, { status: 401 }); const badRequest = () => new Response(BAD_REQUEST_ERROR, { status: 400 }); const empty = () => ({} as Update); -/** - * Abstraction over a request-response cycle, providing access to the update, as - * well as a mechanism for responding to the request and to end it. - */ -export interface ReqResHandler { - /** - * The update object sent from Telegram, usually resolves the request's JSON - * body - */ - update: Promise; - /** - * X-Telegram-Bot-Api-Secret-Token header of the request, or undefined if - * not present - */ - header?: string; - /** - * Ends the request immediately without body, called after every request - * unless a webhook reply was performed - */ - end?: () => void; - /** - * Sends the specified JSON as a payload in the body, used for webhook - * replies - */ - respond: (json: string) => unknown | Promise; - /** - * Responds that the request is unauthorized due to mismatching - * X-Telegram-Bot-Api-Secret-Token headers - */ - unauthorized: () => unknown | Promise; - /** - * Responds that the request is bad due to the body payload not being - * parsable or valid Update object - */ - badRequest: () => unknown | Promise; - /** - * Some frameworks (e.g. Deno's std/http `listenAndServe`) assume that - * handler returns something - */ - handlerReturn?: Promise; +export interface WebhookRequestData { + path(): string; + header(name: string): string | null; + update(): Promise; + extra?(): Promise; } +export type WebhookResponseData = + | { type: "end" } + | { type: "bad-request" } + | { type: "unauthorized" } + | { type: "success"; json?: string }; +// deno-lint-ignore no-explicit-any +export type FrameworkAdapter any> = ( + ...args: Parameters +) => ReqResHandler; +// deno-lint-ignore no-explicit-any +export interface ReqResHandler any> { + receive(...args: Parameters): WebhookRequestData; + ok(...args: Parameters): ReturnType; + badRequest(...args: Parameters): ReturnType; + unauthorized(...args: Parameters): ReturnType; + success(json?: string, ...args: Parameters): ReturnType; +} + +const demo: ReqResHandler<(req: Request) => Response> = { + receive(req) { + return { + path: () => new URL(req.url).pathname, + header: (name) => req.headers.get(name), + update: () => req.json(), + }; + }, + ok, + badRequest, + unauthorized, + success: okJson, +}; +// TODO: refactor the ones below /** AWS lambda serverless functions */ export type LambdaAdapter = ( event: {