middleware icon indicating copy to clipboard operation
middleware copied to clipboard

[zod-openapi] RPC mode fails if handler is not in the router file

Open OxYz0n3 opened this issue 1 year ago • 2 comments

Hello, if I place my handler file in a different file from the route file (I have a Service / Controller architecture), the RPC mode no longer works for auto-completion and keep asking for a “param” as input even if it isn't needed.

Example:

route.ts

import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";

import TestController from "./handler";

const router = new OpenAPIHono()
    .openapi(createRoute({
        path: "/test",
        method: "get",
        description: "Test route",
        request: {},
        responses: {
            200: {
                description: "Success",
                content: {
                    'application/json': {
                        schema: z.object({})
                    }
                }
            }
        }
    }), TestController.Test);

handler.ts

import { Context } from "hono";

class TestController {
    static async Test(c: Context) {
        return (c.json({}, 200));
    }
}

export default TestController;

OxYz0n3 avatar May 15 '24 11:05 OxYz0n3

I fixed, replacing:

static async Test(c: Context) by static async Test<E extends Env>(c: Context<Env>)

OxYz0n3 avatar May 15 '24 12:05 OxYz0n3

Hi @OxYz0n3

You can not write the handler outside from app.openapi(). If so type inference is not enabled.

yusukebe avatar May 15 '24 14:05 yusukebe

Hi @OxYz0n3 Your problem can be solved using RouteHandler.

import { createRoute, OpenAPIHono, type RouteHandler } from '@hono/zod-openapi'

const route = createRoute(...)
const handler: RouteHandler<typeof route> = (c) => {
  return c.json({}, 200)
}
const app = new OpenAPIHono().openapi(route, handler)

akineko avatar May 19 '24 09:05 akineko

I installed the latest version and it works well, thanks a lot!

OxYz0n3 avatar May 19 '24 09:05 OxYz0n3