Skip to content

Commit 3c738f5

Browse files
authored
fix(zod-openapi): replace path param strings correctly in basePath (#992)
* fix(zod-openapi): replace path param strings correctly in basePath * add changeset
1 parent 50936f9 commit 3c738f5

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

.changeset/dry-squids-flash.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@hono/zod-openapi': patch
3+
---
4+
5+
fix: replace path param strings correctly in basePath

packages/zod-openapi/src/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -701,7 +701,7 @@ function addBasePathToDocument(document: Record<string, any>, basePath: string)
701701
const updatedPaths: Record<string, any> = {}
702702

703703
Object.keys(document.paths).forEach((path) => {
704-
updatedPaths[mergePath(basePath, path)] = document.paths[path]
704+
updatedPaths[mergePath(basePath.replaceAll(/:([^\/]+)/g, '{$1}'), path)] = document.paths[path]
705705
})
706706

707707
return {

packages/zod-openapi/test/index.test.ts

+35
Original file line numberDiff line numberDiff line change
@@ -1239,6 +1239,41 @@ describe('basePath()', () => {
12391239

12401240
expect(paths).not.toStrictEqual(['/message1', '/message2', '/hello'])
12411241
})
1242+
1243+
it('Should correctly handle path parameters in basePath', async () => {
1244+
const app = new OpenAPIHono().basePath('/:param')
1245+
1246+
app.openapi(
1247+
createRoute({
1248+
method: 'get',
1249+
path: '/',
1250+
responses: {
1251+
200: {
1252+
description: 'Get message',
1253+
},
1254+
},
1255+
}),
1256+
(c) => {
1257+
return c.json({ path: c.req.param('param') })
1258+
}
1259+
)
1260+
1261+
const json = app.getOpenAPIDocument({
1262+
openapi: '3.0.0',
1263+
info: {
1264+
version: '1.0.0',
1265+
title: 'My API',
1266+
},
1267+
})
1268+
1269+
const paths = Object.keys(json.paths)
1270+
1271+
expect(paths).toStrictEqual(['/{param}'])
1272+
1273+
const res = await app.request('/abc')
1274+
expect(res.status).toBe(200)
1275+
expect(await res.json()).toEqual({ path: 'abc' })
1276+
})
12421277
})
12431278

12441279
describe('With hc', () => {

0 commit comments

Comments
 (0)