I want to create a middleware for hono that requires the previous middleware to have some property.
So currently I'm doing a project that have some path like this: /organization/orgSlug/functions...
So I want all the methods in functions to have a valid org when I'm accessing them. This means that I need to do 2 things:
- Validate that the orgSlug exists in the params
- Validate that the orgSlug is pointing to an actual org.
So since I'm using zod validator it's easy to pop in something like:
Now, I'm writing my own custom middleware that do this:
now how would I define the type for my own middleware ?
I have tinkering and set the
out
type to something like :
and I got type completion for the orgSlug. However I want to also validate that the previous middleware handler need to set that orgSlug params, so for example in case I forgot to put in zValidator or make a typo in the schema, I can catch it.
Is there anyway to do something like that ?5 Replies
there isn't
you can type the downstream middleware so that it "knows" that
org
should be available in Context
, but there's no way to do that type-safely
there's an open issue on github about this, but unfortunately it looks like it would take a redesign of hono's type system to add type checking between middleware, so i wouldn't expect it to be addedah thanks, I kinda got it now after alot of tinkering with the createMiddleware Generic function.
i think you could use the Schema from Hono
you might need to chained it, because it will not be included on type
ah, it's impossible to type-safe cu'z
ctx.set
returns void
it might be possible if ctx.set
can be chained and the params will be stored in Schema or something that can overload the typingsyeah currently I can't do it. Yesterday it works because I have some wrong type in my generic 🤷♂️
your best option is to use something like the
createHandlers
factory to bind the two middleware together, but there's no way to actually type check