honojs / middleware

monorepo for Hono third-party middleware/helpers/wrappers
https://hono.dev
436 stars 154 forks source link

@hono/zod-validator not inferring app context types correctly within it's hook function #719

Open DaveLo opened 1 month ago

DaveLo commented 1 month ago

If i have types passed to the Hono generic like:

type HonoBindings = {
  Bindings: { event:LambdaEvent; lambdaContext: LambdaContext };
  Variables: { logger: PowertoolsLogger }
}

const app = new Hono<HonoBindings>()

If I try to access the logger from within the hook

app.get(
  "/customer", 
  zValidator("query", querySchema, (result, ctx) => {
  // this is type never 
  const logger = ctx.get('logger');
  if (!result.success) {
    logger.debug('Validation error: ',  result.error)
    ctx.text("InvalidRequest", 400);
  }),
  async (ctx) => { // do things }
);

I think I can do this

zValidator<typeof querySchema, 'query', HonoBindings, "?">();

But the typings for the generic are not documented so I'm not sure if that's intended or even what that 4th one is only that it's required and is a string.

I feel like it should infer from it's context, but if inferring them isn't possible I would maybe suggest moving the env type up the list as all the rest of the types seem to infer without trouble.

yusukebe commented 1 month ago

Hi @DaveLo

This is related to https://github.com/honojs/hono/issues/3341 https://github.com/honojs/hono/issues/3202 https://github.com/honojs/hono/issues/3202https://github.com/honojs/hono/issues/3198

DaveLo commented 1 month ago

I see. I guess in that case it might be beneficial to document how to type the generic since it seems unlikely to be fixed.