Question: How to implement smarter middleware type infer on context?
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 25/100
- Issue type
- Feature
- Clarity
- Needs clarification
- Activity status
- Stale
- Tech stack
- typescript
- Domain
- api, backend-api-design
Research direction
Start by reviewing the OpenAPIRoute class model and the middleware definitions involved in route setup. Compare them with Hono's middleware context inference example and determine what compile-time behavior should indicate that a required context variable was not injected; done means the design is documented or implemented with a corresponding type-level verification.
Written by the indexing model from the issue text.
Description
I was using hono-openapi package for openapi, and want to migrate to chanafa, I like chanafa's way to define endpoints with class.
But one big problem I have with chanafa is type inference on context for middleware.
Example (with regular hono code)
export interface AccountContext {
account: NonNullable<Awaited<ReturnType<typeof accountService.getAccount>>>
}
export const withAccountMiddleware = (): MiddlewareHandler<
AppContextTypes & { Variables: AccountContext }
> => {
return async (c, next) => {
const account = await accountService.getAccount(c.req.valid("query").accountId)
c.set("account", account!)
await next()
}
}
const app = new Hono()
app.get("/middleware-demo", withAccountMiddleware(), (c) => {
const account = c.get("account")
return c.json(account)
})
When withAccountMiddleware middleware is added to a route, its context types are automatically inherited.
TypeScript LSP knows c has account and c.get("account") type.
If I didn't add withAccountMiddleware(), then c.get("account") will show error warnings provided by typescript. So I can confidently use account directly without checking null or checking undefined.
But in Chanafa, routing and class endpoints are defined separately, middlewares are defined with routing.
The classes has no prior knowledge of the middlewares added before them.
I have to assume that account exists within a custom Context.
type AccountBindings = {
Variables: {
binanceAPI: BinanceAPI
account: NonNullable<Awaited<ReturnType<typeof accountService.getAccount>>>
}
}
type AppContextWithAccount = Context<AccountBindings>
class Endpint extends OpenAPIRoute {
async handle(c: AppContextWithAccount) {
const account = c.get("account")
...
}
}
If I forgot to add the middleware to inject account into context, there is no compile time warning. I will have to find out in runtime, with manual testing, unit testing or production environment error.
So I have to check whether account is null or undefined.
A slightly better solution:
The best workaround I found so far is to make an abstract class route like this, and call this.getAccount() instead of c.get("account"). So at least in runtime I get a proper error but not error with un-informative message like trying to access field "x" on undefined.
abstract class BinanceAccountRoute extends OpenAPIRoute {
// Type-safe getter for account - will cause compile error if context doesn't have it
protected getAccount(c: AppContextWithAccount) {
const account = c.get("account")
if (!account) {
throw new HTTPException(500, { message: "Account not available in context" })
}
return account
}
// Override the handle method signature to require AppContextWithAccount
abstract handle(c: AppContextWithAccount): Promise<any> | any
}
However this is still not ideal, the error could only be detected in runtime, not compile time.
- Dominant language
- TypeScript
- Stars
- 777
- Forks
- 74
- Avg merge
- 16h 30m
- Merged PRs (30d)
- 27
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from cloudflare/chanfana
-
Hono path parameters with a regex pattern keep the pattern in the OpenAPI pathPossibly taken @0z5a claimed this today. Open
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
cloudflare/chanfana#400 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
cloudflare/chanfana#287 ·
Maintainers usually reply within 1 day
-
Difficulty 5/5 Over a week Newbie friendliness 42/100
cloudflare/chanfana#345 ·
Maintainers usually reply within 1 day
-
Difficulty 4/5 3-5 days Newbie friendliness 35/100
cloudflare/chanfana#336 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 4/5 3-5 days Newbie friendliness 35/100
cloudflare/chanfana#285 ·
Maintainers usually reply within 1 day
All issues in cloudflare/chanfana
Similar issues
-
kind:defect
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 66/100
mux-labs/mux-frontend#1240 ·
Maintainers usually reply within 1 day
-
area: agents-mcp priority: normal
Difficulty 2/5 1-3 hours Newbie friendliness 64/100
Maintainers usually reply within 1 day
-
Wait for the IDS correction dialog to settle in the stale-audit testPossibly taken @louistrue claimed this today. Openready
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Maintainers usually reply within 1 day
-
Top-bar LanguagePicker: a failed language save rolls back silentlyPossibly taken @ShivamJuyal24 claimed this today. Openaccessibility admin bug
Difficulty 2/5 Half a day Newbie friendliness 70/100
endora-commerce/endora-commerce#1769 · 1 comment ·
Maintainers usually reply within 1 day