Skip to content

Commit

Permalink
Add support for hono.on(method, path, class) (#208)
Browse files Browse the repository at this point in the history
  • Loading branch information
G4brym authored Dec 5, 2024
1 parent 83366c7 commit 9d9325e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "chanfana",
"version": "2.4.1",
"version": "2.4.2",
"description": "OpenAPI 3 and 3.1 schema generator and validator for Hono, itty-router and more!",
"main": "dist/index.js",
"module": "dist/index.mjs",
Expand Down
23 changes: 22 additions & 1 deletion src/adapters/hono.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { OpenAPIHandler, type OpenAPIRouterType } from "../openapi";
import type { OpenAPIRoute } from "../route";
import type { RouterOptions } from "../types";

export type HonoOpenAPIRouterType<M> = OpenAPIRouterType<M> & {
on(method: string, path: string, endpoint: typeof OpenAPIRoute<any>): M;
on(method: string, path: string, router: M): M;
};

export class HonoOpenAPIHandler extends OpenAPIHandler {
getRequest(args: any[]) {
return args[0].req.raw;
Expand All @@ -11,7 +17,7 @@ export class HonoOpenAPIHandler extends OpenAPIHandler {
}
}

export function fromHono<M>(router: M, options?: RouterOptions): M & OpenAPIRouterType<M> {
export function fromHono<M>(router: M, options?: RouterOptions): M & HonoOpenAPIRouterType<M> {
const openapiRouter = new HonoOpenAPIHandler(router, options);

return new Proxy(router, {
Expand All @@ -35,6 +41,21 @@ export function fromHono<M>(router: M, options?: RouterOptions): M & OpenAPIRout
path: route,
handlers: handlers,
});
} else if (prop === "on") {
const methods: string | string[] = route;
const paths: string | string[] = handlers.shift();

if (Array.isArray(methods) || Array.isArray(paths)) {
throw new Error("chanfana only supports single method+path on hono.on('method', 'path', EndpointClass)");
}

handlers = openapiRouter.registerRoute({
method: methods.toLowerCase(),
path: paths,
handlers: handlers,
});

handlers = [paths, ...handlers];
}
}

Expand Down

0 comments on commit 9d9325e

Please sign in to comment.