fix(zod-openapi): correctly handle path parameters in basePath (#995)

* fix(zod-openapi): correctly handle path parameters in basePath
This tries to fix an issue not covered by #992.

* chore: add changeset
pull/997/head
Lucas 2025-03-02 22:02:43 +01:00 committed by GitHub
parent 10d65d1828
commit c279ba2bc5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 54 additions and 2 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-openapi': patch
---
fix(zod-openapi): correctly handle path parameters in basePath

View File

@ -638,7 +638,7 @@ export class OpenAPIHono<
path: mergePath( path: mergePath(
pathForOpenAPI, pathForOpenAPI,
// @ts-expect-error _basePath is private // @ts-expect-error _basePath is private
app._basePath, app._basePath.replaceAll(/:([^\/]+)/g, '{$1}'),
def.route.path def.route.path
), ),
}) })
@ -649,7 +649,7 @@ export class OpenAPIHono<
path: mergePath( path: mergePath(
pathForOpenAPI, pathForOpenAPI,
// @ts-expect-error _basePath is private // @ts-expect-error _basePath is private
app._basePath, app._basePath.replaceAll(/:([^\/]+)/g, '{$1}'),
def.webhook.path def.webhook.path
), ),
}) })

View File

@ -1274,6 +1274,53 @@ describe('basePath()', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.json()).toEqual({ path: 'abc' }) expect(await res.json()).toEqual({ path: 'abc' })
}) })
it('Should correctly handle path parameters in nested basePath', async () => {
const app = new OpenAPIHono()
const nested = new OpenAPIHono().basePath('/:param2')
nested.openapi(
createRoute({
method: 'get',
path: '/{param3}',
responses: {
200: {
description: 'Get message',
},
},
}),
(c) => {
return c.json({
param1: c.req.param('param1'),
param2: c.req.param('param2'),
param3: c.req.param('param3')
})
}
)
app.route('/:param1', nested)
const json = app.getOpenAPIDocument({
openapi: '3.0.0',
info: {
version: '1.0.0',
title: 'My API',
},
})
const paths = Object.keys(json.paths)
expect(paths).toStrictEqual(['/{param1}/{param2}/{param3}'])
expect(paths).not.toStrictEqual(['/{param1}/:param2/{param3}'])
const res = await app.request('/foo/bar/baz')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
param1: 'foo',
param2: 'bar',
param3: 'baz'
})
})
}) })
describe('With hc', () => { describe('With hc', () => {