From 3c738f5ea44f5f5e5cdc14dfeaba5c04188d6373 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Sun, 2 Mar 2025 17:48:35 +0900 Subject: [PATCH] fix(zod-openapi): replace path param strings correctly in basePath (#992) * fix(zod-openapi): replace path param strings correctly in basePath * add changeset --- .changeset/dry-squids-flash.md | 5 ++++ packages/zod-openapi/src/index.ts | 2 +- packages/zod-openapi/test/index.test.ts | 35 +++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 .changeset/dry-squids-flash.md diff --git a/.changeset/dry-squids-flash.md b/.changeset/dry-squids-flash.md new file mode 100644 index 00000000..90d10cd1 --- /dev/null +++ b/.changeset/dry-squids-flash.md @@ -0,0 +1,5 @@ +--- +'@hono/zod-openapi': patch +--- + +fix: replace path param strings correctly in basePath diff --git a/packages/zod-openapi/src/index.ts b/packages/zod-openapi/src/index.ts index cedde6a4..59b905b6 100644 --- a/packages/zod-openapi/src/index.ts +++ b/packages/zod-openapi/src/index.ts @@ -701,7 +701,7 @@ function addBasePathToDocument(document: Record, basePath: string) const updatedPaths: Record = {} Object.keys(document.paths).forEach((path) => { - updatedPaths[mergePath(basePath, path)] = document.paths[path] + updatedPaths[mergePath(basePath.replaceAll(/:([^\/]+)/g, '{$1}'), path)] = document.paths[path] }) return { diff --git a/packages/zod-openapi/test/index.test.ts b/packages/zod-openapi/test/index.test.ts index 5a866745..8d29402a 100644 --- a/packages/zod-openapi/test/index.test.ts +++ b/packages/zod-openapi/test/index.test.ts @@ -1239,6 +1239,41 @@ describe('basePath()', () => { expect(paths).not.toStrictEqual(['/message1', '/message2', '/hello']) }) + + it('Should correctly handle path parameters in basePath', async () => { + const app = new OpenAPIHono().basePath('/:param') + + app.openapi( + createRoute({ + method: 'get', + path: '/', + responses: { + 200: { + description: 'Get message', + }, + }, + }), + (c) => { + return c.json({ path: c.req.param('param') }) + } + ) + + 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(['/{param}']) + + const res = await app.request('/abc') + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ path: 'abc' }) + }) }) describe('With hc', () => {