diff --git a/.changeset/fluffy-shoes-walk.md b/.changeset/fluffy-shoes-walk.md new file mode 100644 index 00000000..dbe72c5c --- /dev/null +++ b/.changeset/fluffy-shoes-walk.md @@ -0,0 +1,5 @@ +--- +'@hono/zod-openapi': patch +--- + +fix: support a base path diff --git a/packages/zod-openapi/src/index.ts b/packages/zod-openapi/src/index.ts index 7b89ab1d..7c08bdef 100644 --- a/packages/zod-openapi/src/index.ts +++ b/packages/zod-openapi/src/index.ts @@ -1,7 +1,6 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-unused-vars */ import type { - ResponseConfig, RouteConfig as RouteConfigBase, ZodContentObject, ZodMediaTypeObject, @@ -37,7 +36,7 @@ import type { SuccessStatusCode, } from 'hono/utils/http-status' import { mergePath } from 'hono/utils/url' -import type { AnyZodObject, ZodError, ZodSchema } from 'zod' +import type { ZodError, ZodSchema } from 'zod' import { ZodType, z } from 'zod' type MaybePromise = Promise | T @@ -405,16 +404,22 @@ export class OpenAPIHono< return this } - getOpenAPIDocument = (config: OpenAPIObjectConfig) => { + getOpenAPIDocument = ( + config: OpenAPIObjectConfig + ): ReturnType => { const generator = new OpenApiGeneratorV3(this.openAPIRegistry.definitions) const document = generator.generateDocument(config) - return document + // @ts-expect-error the _basePath is a private property + return this._basePath ? addBasePathToDocument(document, this._basePath) : document } - getOpenAPI31Document = (config: OpenAPIObjectConfig) => { + getOpenAPI31Document = ( + config: OpenAPIObjectConfig + ): ReturnType => { const generator = new OpenApiGeneratorV31(this.openAPIRegistry.definitions) const document = generator.generateDocument(config) - return document + // @ts-expect-error the _basePath is a private property + return this._basePath ? addBasePathToDocument(document, this._basePath) : document } doc =

( @@ -533,3 +538,16 @@ export const createRoute =

, basePath: string) { + const updatedPaths: Record = {} + + Object.keys(document.paths).forEach((path) => { + updatedPaths[mergePath(basePath, path)] = document.paths[path] + }) + + return { + ...document, + paths: updatedPaths, + } +} diff --git a/packages/zod-openapi/test/index.test.ts b/packages/zod-openapi/test/index.test.ts index c0c91974..c8756a9d 100644 --- a/packages/zod-openapi/test/index.test.ts +++ b/packages/zod-openapi/test/index.test.ts @@ -873,6 +873,13 @@ describe('basePath()', () => { expect(client.api.message.$url().pathname).toBe('/api/message') }) + + it('Should add the base path to paths', async () => { + const res = await app.request('/api/doc') + expect(res.status).toBe(200) + const data = (await res.json()) as any + expect(Object.keys(data.paths)[0]).toBe('/api/message') + }) }) describe('With hc', () => {