From d5166dd85165d0a9e6e801c505ea6f1475243bf7 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Fri, 11 Oct 2024 05:42:05 +0900 Subject: [PATCH] fix(factory): relax Bindings and Variables for `createMiddleware` (#3498) * feat(factory): relax Bindings and Variables types * add a break --- src/helper/factory/index.test.ts | 30 ++++++++++++++++++++++++++++++ src/helper/factory/index.ts | 17 ++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/helper/factory/index.test.ts b/src/helper/factory/index.test.ts index 514fc172..b636c8b6 100644 --- a/src/helper/factory/index.test.ts +++ b/src/helper/factory/index.test.ts @@ -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', () => { diff --git a/src/helper/factory/index.ts b/src/helper/factory/index.ts index c5fe7a86..9680c939 100644 --- a/src/helper/factory/index.ts +++ b/src/helper/factory/index.ts @@ -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 = (app: Hono) => void @@ -237,10 +238,20 @@ export const createFactory = (init? initApp?: InitApp }): Factory => new Factory(init) +// Add `any` if it's undefined to relax types +// { Variables: Variables } => { Bindings: any, Variables: any } +// { Bindings: Bindings } => { Bindings: Bindings, Variables: any } + +type AddAnyToEnv = { + 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> >( - middleware: MiddlewareHandler -): MiddlewareHandler => createFactory().createMiddleware(middleware) + middleware: MiddlewareHandler +): MiddlewareHandler => createFactory().createMiddleware(middleware)