Skip to content

Commit c279ba2

Browse files
authored
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
1 parent 10d65d1 commit c279ba2

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

.changeset/smooth-grapes-pay.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@hono/zod-openapi': patch
3+
---
4+
5+
fix(zod-openapi): correctly handle path parameters in basePath

packages/zod-openapi/src/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ export class OpenAPIHono<
638638
path: mergePath(
639639
pathForOpenAPI,
640640
// @ts-expect-error _basePath is private
641-
app._basePath,
641+
app._basePath.replaceAll(/:([^\/]+)/g, '{$1}'),
642642
def.route.path
643643
),
644644
})
@@ -649,7 +649,7 @@ export class OpenAPIHono<
649649
path: mergePath(
650650
pathForOpenAPI,
651651
// @ts-expect-error _basePath is private
652-
app._basePath,
652+
app._basePath.replaceAll(/:([^\/]+)/g, '{$1}'),
653653
def.webhook.path
654654
),
655655
})

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

+47
Original file line numberDiff line numberDiff line change
@@ -1274,6 +1274,53 @@ describe('basePath()', () => {
12741274
expect(res.status).toBe(200)
12751275
expect(await res.json()).toEqual({ path: 'abc' })
12761276
})
1277+
1278+
it('Should correctly handle path parameters in nested basePath', async () => {
1279+
const app = new OpenAPIHono()
1280+
const nested = new OpenAPIHono().basePath('/:param2')
1281+
1282+
nested.openapi(
1283+
createRoute({
1284+
method: 'get',
1285+
path: '/{param3}',
1286+
responses: {
1287+
200: {
1288+
description: 'Get message',
1289+
},
1290+
},
1291+
}),
1292+
(c) => {
1293+
return c.json({
1294+
param1: c.req.param('param1'),
1295+
param2: c.req.param('param2'),
1296+
param3: c.req.param('param3')
1297+
})
1298+
}
1299+
)
1300+
1301+
app.route('/:param1', nested)
1302+
1303+
const json = app.getOpenAPIDocument({
1304+
openapi: '3.0.0',
1305+
info: {
1306+
version: '1.0.0',
1307+
title: 'My API',
1308+
},
1309+
})
1310+
1311+
const paths = Object.keys(json.paths)
1312+
1313+
expect(paths).toStrictEqual(['/{param1}/{param2}/{param3}'])
1314+
expect(paths).not.toStrictEqual(['/{param1}/:param2/{param3}'])
1315+
1316+
const res = await app.request('/foo/bar/baz')
1317+
expect(res.status).toBe(200)
1318+
expect(await res.json()).toEqual({
1319+
param1: 'foo',
1320+
param2: 'bar',
1321+
param3: 'baz'
1322+
})
1323+
})
12771324
})
12781325

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

0 commit comments

Comments
 (0)