2024-11-16 08:46:13 +08:00
|
|
|
import type { MiddlewareHandler } from 'hono'
|
2024-05-18 23:58:15 +08:00
|
|
|
import type { RouteHandler } from '../src'
|
2024-05-15 15:51:34 +08:00
|
|
|
import { OpenAPIHono, createRoute, z } from '../src'
|
|
|
|
|
2024-05-18 23:58:15 +08:00
|
|
|
describe('supports async handler', () => {
|
2024-05-15 15:51:34 +08:00
|
|
|
const route = createRoute({
|
|
|
|
method: 'get',
|
|
|
|
path: '/users',
|
|
|
|
responses: {
|
|
|
|
200: {
|
|
|
|
content: {
|
|
|
|
'application/json': {
|
|
|
|
schema: z.object({
|
|
|
|
id: z.string(),
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
description: 'Retrieve the user',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2024-05-18 23:58:15 +08:00
|
|
|
test('argument of openapi method', () => {
|
|
|
|
const hono = new OpenAPIHono()
|
|
|
|
|
|
|
|
hono.openapi(route, (c) => {
|
|
|
|
return c.json({
|
|
|
|
id: '123',
|
|
|
|
})
|
2024-05-15 15:51:34 +08:00
|
|
|
})
|
|
|
|
|
2024-05-18 23:58:15 +08:00
|
|
|
hono.openapi(route, async (c) => {
|
|
|
|
return c.json({
|
|
|
|
id: '123',
|
|
|
|
})
|
2024-05-15 15:51:34 +08:00
|
|
|
})
|
|
|
|
})
|
2024-05-18 23:58:15 +08:00
|
|
|
|
|
|
|
test('RouteHandler type', () => {
|
|
|
|
const handler: RouteHandler<typeof route> = (c) => {
|
|
|
|
return c.json({
|
|
|
|
id: '123',
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const asyncHandler: RouteHandler<typeof route> = async (c) => {
|
|
|
|
return c.json({
|
|
|
|
id: '123',
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const hono = new OpenAPIHono()
|
|
|
|
hono.openapi(route, handler)
|
|
|
|
hono.openapi(route, asyncHandler)
|
|
|
|
})
|
2024-11-16 08:46:13 +08:00
|
|
|
|
|
|
|
test('RouteHandler infers env type from middleware', () => {
|
|
|
|
type CustomEnv = { Variables: { customKey: string } }
|
|
|
|
|
|
|
|
const customMiddleware: MiddlewareHandler<CustomEnv> = (c, next) => {
|
|
|
|
c.set('customKey', 'customValue')
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
|
|
|
const routeWithMiddleware = createRoute({
|
|
|
|
method: 'get',
|
|
|
|
path: '/users',
|
|
|
|
middleware: [customMiddleware] as const,
|
|
|
|
responses: {
|
|
|
|
200: {
|
|
|
|
content: {
|
|
|
|
'application/json': {
|
|
|
|
schema: z.object({
|
|
|
|
id: z.string(),
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
description: 'Retrieve the user',
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
const handler: RouteHandler<typeof routeWithMiddleware> = (c) => {
|
|
|
|
return c.json({
|
|
|
|
id: c.get('customKey'),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const hono = new OpenAPIHono()
|
|
|
|
hono.openapi(routeWithMiddleware, handler)
|
|
|
|
})
|
2024-05-15 15:51:34 +08:00
|
|
|
})
|