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:
zValidator(param, orgParamSchema).
zValidator(param, orgParamSchema).
Now, I'm writing my own custom middleware that do this:
async (c, next) => {
// retrieve org repository
// retrieve org in db
// set org into variable : c.set('org', org)
}
async (c, next) => {
// retrieve org repository
// retrieve org in db
// set org into variable : c.set('org', org)
}
now how would I define the type for my own middleware ? I have tinkering and set the out type to something like :
out: {
params: {
orgSlug: string
}
}
out: {
params: {
orgSlug: string
}
}
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
ambergristle
ambergristle4mo ago
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 added
山 Đỗ Đình Thy Sơn
ah thanks, I kinda got it now after alot of tinkering with the createMiddleware Generic function.
Lazuee
Lazuee4mo ago
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 typings
山 Đỗ Đình Thy Sơn
yeah currently I can't do it. Yesterday it works because I have some wrong type in my generic 🤷‍♂️
ambergristle
ambergristle4mo ago
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

Did you find this page helpful?