From d897485021271734c54925da53e829689ae06838 Mon Sep 17 00:00:00 2001 From: Jonas Bach Date: Tue, 25 Jul 2023 15:11:37 +0200 Subject: [PATCH] fix(#178): handle $ref in response object --- .changeset/quick-jeans-hope.md | 5 ++ lib/src/getZodiosEndpointDefinitionList.ts | 4 +- lib/tests/resolve-ref-responses.test.ts | 59 ++++++++++++++++++++++ 3 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 .changeset/quick-jeans-hope.md create mode 100644 lib/tests/resolve-ref-responses.test.ts diff --git a/.changeset/quick-jeans-hope.md b/.changeset/quick-jeans-hope.md new file mode 100644 index 0000000..3d309e1 --- /dev/null +++ b/.changeset/quick-jeans-hope.md @@ -0,0 +1,5 @@ +--- +"openapi-zod-client": minor +--- + +handle $ref in responses object diff --git a/lib/src/getZodiosEndpointDefinitionList.ts b/lib/src/getZodiosEndpointDefinitionList.ts index 0fccdb6..2ce87e3 100644 --- a/lib/src/getZodiosEndpointDefinitionList.ts +++ b/lib/src/getZodiosEndpointDefinitionList.ts @@ -281,7 +281,9 @@ export const getZodiosEndpointDefinitionList = (doc: OpenAPIObject, options?: Te } for (const statusCode in operation.responses) { - const responseItem = operation.responses[statusCode] as ResponseObject; + const responseItem = ( + isReferenceObject(operation.responses[statusCode]) ? ctx.resolver.getSchemaByRef(operation.responses[statusCode].$ref) : operation.responses[statusCode] + ) as ResponseObject; const mediaTypes = Object.keys(responseItem.content ?? {}); const matchingMediaType = mediaTypes.find(isMediaTypeAllowed); diff --git a/lib/tests/resolve-ref-responses.test.ts b/lib/tests/resolve-ref-responses.test.ts new file mode 100644 index 0000000..9599888 --- /dev/null +++ b/lib/tests/resolve-ref-responses.test.ts @@ -0,0 +1,59 @@ +import { getZodiosEndpointDefinitionList } from "../src"; +import { expect, test } from "vitest"; + +test("resolve-ref-responses", () => { + // Without the refiner function passed. + expect( + getZodiosEndpointDefinitionList({ + openapi: "3.0.3", + info: { version: "1", title: "Example API" }, + paths: { + "/": { + get: { + operationId: "getExample", + responses: { + "200": { + $ref: "#/components/responses/ExampleResponse" + }, + }, + }, + }, + }, + components: { + responses: { + ExampleResponse: { + description: "example response", + content: { "application/json": { schema: { type: "string" } } }, + } + } + }, + }) + ).toMatchInlineSnapshot(` + { + "deepDependencyGraph": {}, + "endpoints": [ + { + "description": undefined, + "errors": [], + "method": "get", + "parameters": [], + "path": "/", + "requestFormat": "json", + "response": "z.string()", + }, + ], + "issues": { + "ignoredFallbackResponse": [], + "ignoredGenericError": [], + }, + "refsDependencyGraph": {}, + "resolver": { + "getSchemaByRef": [Function], + "resolveRef": [Function], + "resolveSchemaName": [Function], + }, + "schemaByName": {}, + "zodSchemaByName": {}, + } + `); +});