Skip to content

Commit

Permalink
feat: implement a lof of frameworks handler
Browse files Browse the repository at this point in the history
  • Loading branch information
kravetsone committed Jul 10, 2024
1 parent 87b85ef commit 47c5090
Showing 1 changed file with 34 additions and 9 deletions.
43 changes: 34 additions & 9 deletions src/webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,32 @@ export type FrameworkAdapter = (...args: any[]) => FrameworkHandler;

export const frameworks = {
elysia: ({ body }) => ({ body, response: () => responseOK }),
fastify: (request, reply) => ({
body: request.body,
response: () => reply.send("OK"),
}),
hono: (c) => ({ body: c.req.json(), response: () => c.text("OK") }),
express: (req, res) => ({ body: req.body, response: () => res.send("OK") }),
koa: (ctx) => ({
body: ctx.request.body,
response: () => {
ctx.body = "OK";
},
}),
http: (req, res) => ({
body: new Promise((resolve) => {
let body = "";

req.on("data", (chunk: Buffer) => {
body += chunk.toString();
});

req.on("end", () => resolve(JSON.parse(body)));
}),
response: () => res.writeHead(200).end("OK"),
}),
"std/http": (req) => ({ body: req.json(), response: () => responseOK }),
"Bun.serve": (req) => ({ body: req.json(), response: () => responseOK }),
} satisfies Record<string, FrameworkAdapter>;

export function webhookHandler<Framework extends keyof typeof frameworks>(
Expand All @@ -20,7 +46,7 @@ export function webhookHandler<Framework extends keyof typeof frameworks>(
) {
const frameworkAdapter = frameworks[framework];

return async (...args: any[]) => {
return (async (...args: any[]) => {
const { body, response } = frameworkAdapter(
// @ts-expect-error
...args,
Expand All @@ -29,12 +55,11 @@ export function webhookHandler<Framework extends keyof typeof frameworks>(
await tKassa.emit(await body);

if (response) return response();
};
// as unknown as ReturnType<(typeof frameworks)[Framework]> extends {
// response: () => any;
// }
// ? (
// ...args: Parameters<(typeof frameworks)[Framework]>
// ) => ReturnType<ReturnType<(typeof frameworks)[Framework]>["response"]>
// : (...args: Parameters<(typeof frameworks)[Framework]>) => void;
}) as ReturnType<(typeof frameworks)[Framework]> extends {
response: () => any;
}
? (
...args: Parameters<(typeof frameworks)[Framework]>
) => ReturnType<ReturnType<(typeof frameworks)[Framework]>["response"]>
: (...args: Parameters<(typeof frameworks)[Framework]>) => void;
}

0 comments on commit 47c5090

Please sign in to comment.