mirror of
https://github.com/honojs/hono.git
synced 2024-11-21 18:18:57 +01:00
fix(factory): relax Bindings and Variables for createMiddleware
(#3498)
* feat(factory): relax Bindings and Variables types * add a break
This commit is contained in:
parent
31b4cd414c
commit
d5166dd851
@ -36,6 +36,36 @@ describe('createMiddleware', () => {
|
||||
const url = client.message.$url()
|
||||
expect(url.pathname).toBe('/message')
|
||||
})
|
||||
|
||||
describe('Relax types for Bindings and Variables', () => {
|
||||
it('Should not throw a type error', () => {
|
||||
type Bindings = {
|
||||
MY_VAR_IN_BINDINGS: string
|
||||
}
|
||||
|
||||
const app = new Hono<{ Bindings: Bindings }>()
|
||||
|
||||
type Variables = {
|
||||
MY_VAR: string
|
||||
}
|
||||
|
||||
const middleware = (_variable: string) =>
|
||||
createMiddleware<{ Variables: Variables }>(async (c, next) => {
|
||||
await next()
|
||||
})
|
||||
|
||||
app.get(
|
||||
'/',
|
||||
createMiddleware<{ Bindings: Bindings }>(async (c, next) => {
|
||||
const mw = middleware(c.env.MY_VAR_IN_BINDINGS)
|
||||
await mw(c, next) // `c` does not throw an error
|
||||
}),
|
||||
(c) => {
|
||||
return c.json({})
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('createHandler', () => {
|
||||
|
@ -6,6 +6,7 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { Hono } from '../../hono'
|
||||
import type { Env, H, HandlerResponse, Input, MiddlewareHandler } from '../../types'
|
||||
import type { Simplify } from '../../utils/types'
|
||||
|
||||
type InitApp<E extends Env = Env> = (app: Hono<E>) => void
|
||||
|
||||
@ -237,10 +238,20 @@ export const createFactory = <E extends Env = any, P extends string = any>(init?
|
||||
initApp?: InitApp<E>
|
||||
}): Factory<E, P> => new Factory<E, P>(init)
|
||||
|
||||
// Add `any` if it's undefined to relax types
|
||||
// { Variables: Variables } => { Bindings: any, Variables: any }
|
||||
// { Bindings: Bindings } => { Bindings: Bindings, Variables: any }
|
||||
|
||||
type AddAnyToEnv<T extends { Variables?: object; Bindings?: object }> = {
|
||||
Bindings: undefined extends T['Bindings'] ? any : T['Bindings']
|
||||
Variables: undefined extends T['Variables'] ? any : T['Variables']
|
||||
}
|
||||
|
||||
export const createMiddleware = <
|
||||
E extends Env = any,
|
||||
P extends string = string,
|
||||
I extends Input = {}
|
||||
I extends Input = {},
|
||||
E2 extends Env = Simplify<AddAnyToEnv<E>>
|
||||
>(
|
||||
middleware: MiddlewareHandler<E, P, I>
|
||||
): MiddlewareHandler<E, P, I> => createFactory<E, P>().createMiddleware<I>(middleware)
|
||||
middleware: MiddlewareHandler<E2, P, I>
|
||||
): MiddlewareHandler<E2, P, I> => createFactory<E2, P>().createMiddleware<I>(middleware)
|
||||
|
Loading…
Reference in New Issue
Block a user