fix(zod-openapi): multi-middleware complex type inference (#849)

pull/851/head
Anthony Skorupskyy 2024-11-27 19:54:26 -06:00 committed by GitHub
parent 83cc76469e
commit 4ebecc6142
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 43 additions and 2 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-openapi': patch
---
Fix multi-middleware complex object type inference

View File

@ -221,7 +221,9 @@ type AsArray<T> = T extends undefined // TODO move to utils?
*/
export type DeepSimplify<T> = {
// TODO move to utils?
[KeyType in keyof T]: T[KeyType] extends object ? DeepSimplify<T[KeyType]> : T[KeyType]
[KeyType in keyof T]: T[KeyType] extends Record<string, unknown>
? DeepSimplify<T[KeyType]>
: T[KeyType]
} & {}
/**

View File

@ -1,5 +1,7 @@
import type { MiddlewareHandler } from 'hono'
import type { RouteHandler } from '../src'
import type { Equal, Expect } from 'hono/utils/types'
import type { MiddlewareToHandlerType, OfHandlerType, RouteHandler } from '../src'
import { OpenAPIHono, createRoute, z } from '../src'
describe('supports async handler', () => {
@ -89,4 +91,36 @@ describe('supports async handler', () => {
const hono = new OpenAPIHono()
hono.openapi(routeWithMiddleware, handler)
})
test('RouteHandler infers complex objects from multiple middleware handlers', () => {
// https://github.com/honojs/middleware/issues/847
type CustomEnv = { Variables: { session: { id: string; createdAt: Date } } }
const setSessionMiddleware: MiddlewareHandler<CustomEnv> = (c, next) => {
c.set('session', { id: '8e760fe8-f064-4929-b632-737f88213e57', createdAt: new Date() })
return next()
}
const validateSessionMiddleware: MiddlewareHandler<CustomEnv> = async (c, next) => {
const session = c.get('session')
if ((new Date().getTime() - session.createdAt.getTime()) / 1000 / 60 / 60 > 1) {
return c.json({ message: 'Unauthorized' }, 401)
}
return await next()
}
type Example = MiddlewareToHandlerType<
[typeof setSessionMiddleware, typeof validateSessionMiddleware]
>
// ensure the first defined env does not lose its type in multi-middleware handler
type Verify = Expect<
Equal<
OfHandlerType<Example>['env'],
{
Variables: CustomEnv['Variables']
}
>
>
})
})