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

[zod-openapi] Route with middleware doesn't infer context variables #715

Open
markkkkas opened this issue Aug 25, 2024 · 2 comments
Open

Comments

@markkkkas
Copy link

markkkkas commented Aug 25, 2024

Hey, thanks for the neat tool for effortlessly building OpenAPI schemas. I've noticed (or maybe I'm doing something wrong) that middleware with context variables is not inferred at the route level when trying to access the route's context object.

export type AuthMiddlewareEnv = {
  Variables: {
    user: {
      id: string;
    };
  };
};

export const authMiddleware = createMiddleware<AuthMiddlewareEnv>(
  async (c, next) => {
    const authToken = getCookie(c, Config.Cookie.AuthToken);
    if (!authToken) {
      throw new HTTPException(401);
    }

    const { sub } = await verifyToken(authToken);
    const user = { id: sub };

    c.set("user", user);
    await next();
  }
);

// ...

export const getSessionRoute = createRoute({
  method: "get",
  path: "/session",
  summary: "Get Session",
  middleware: authMiddleware,
  tags,
  responses,
});

// ...

const router = new OpenAPIHono();

router.openapi(getSessionRoute, (c) => c.json(c.var.user)); 
// Property 'user' does not exist on type 'Readonly<ContextVariableMap & object>'

Thanks in advance!

@yusukebe
Copy link
Member

yusukebe commented Sep 12, 2024

Hi @markkkkas

Thank you for the issue. When we solve this problem, the type definition inside the Zod OpenAPI may be super complicated or verbose. I think finding a nice workaround is good for this issue, though I don't have an idea now.

@abielzulio
Copy link

abielzulio commented Sep 18, 2024

Any updates on this?

Updates:
What I did to make it work was simply adding the AuthMiddlewareEnv type to the OpenAPIHono initiation, so it looks like this:

const router = new OpenAPIHono<AuthMiddlewareEnv>();

I'm not sure if this is scalable (as we need to do it on repeat). What do you think? @yusukebe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants