|
1 | 1 | import type { MiddlewareHandler } from 'hono'
|
2 |
| -import type { RouteHandler } from '../src' |
| 2 | +import type { Equal, Expect } from 'hono/utils/types' |
| 3 | +import type { MiddlewareToHandlerType, OfHandlerType, RouteHandler } from '../src' |
| 4 | + |
3 | 5 | import { OpenAPIHono, createRoute, z } from '../src'
|
4 | 6 |
|
5 | 7 | describe('supports async handler', () => {
|
@@ -89,4 +91,36 @@ describe('supports async handler', () => {
|
89 | 91 | const hono = new OpenAPIHono()
|
90 | 92 | hono.openapi(routeWithMiddleware, handler)
|
91 | 93 | })
|
| 94 | + |
| 95 | + test('RouteHandler infers complex objects from multiple middleware handlers', () => { |
| 96 | + // https://github.com/honojs/middleware/issues/847 |
| 97 | + type CustomEnv = { Variables: { session: { id: string; createdAt: Date } } } |
| 98 | + |
| 99 | + const setSessionMiddleware: MiddlewareHandler<CustomEnv> = (c, next) => { |
| 100 | + c.set('session', { id: '8e760fe8-f064-4929-b632-737f88213e57', createdAt: new Date() }) |
| 101 | + return next() |
| 102 | + } |
| 103 | + |
| 104 | + const validateSessionMiddleware: MiddlewareHandler<CustomEnv> = async (c, next) => { |
| 105 | + const session = c.get('session') |
| 106 | + if ((new Date().getTime() - session.createdAt.getTime()) / 1000 / 60 / 60 > 1) { |
| 107 | + return c.json({ message: 'Unauthorized' }, 401) |
| 108 | + } |
| 109 | + return await next() |
| 110 | + } |
| 111 | + |
| 112 | + type Example = MiddlewareToHandlerType< |
| 113 | + [typeof setSessionMiddleware, typeof validateSessionMiddleware] |
| 114 | + > |
| 115 | + |
| 116 | + // ensure the first defined env does not lose its type in multi-middleware handler |
| 117 | + type Verify = Expect< |
| 118 | + Equal< |
| 119 | + OfHandlerType<Example>['env'], |
| 120 | + { |
| 121 | + Variables: CustomEnv['Variables'] |
| 122 | + } |
| 123 | + > |
| 124 | + > |
| 125 | + }) |
92 | 126 | })
|
0 commit comments