From 4cc89b7f7ff6cda1fa4a2a7e79afb37407b3d324 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Fri, 5 Jun 2026 11:54:22 +0200 Subject: [PATCH 1/4] Add tests --- .../OpenApi/OpenApiIntegrationTests.cs | 124 ++++++++++++++++++ ...enApi_Includes_Initial_Routes_NET10_0.json | 65 +++++---- ...ncludes_Initial_Routes_NET10_0_Fusion.json | 65 +++++---- ...penApi_Includes_Initial_Routes_NET9_0.json | 65 +++++---- ...Includes_Initial_Routes_NET9_0_Fusion.json | 65 +++++---- ..._Input_Type_Via_Mutation_Body_NET10_0.json | 75 +++++++++++ ...t_Input_Type_Via_Mutation_Body_NET9_0.json | 70 ++++++++++ ..._With_Two_Sibling_Occurrences_NET10_0.json | 64 +++++++++ ...e_With_Two_Sibling_Occurrences_NET9_0.json | 59 +++++++++ ...ndirect_Output_Type_Via_Query_NET10_0.json | 84 ++++++++++++ ...Indirect_Output_Type_Via_Query_NET9_0.json | 74 +++++++++++ ..._Input_Type_Via_Mutation_Body_NET10_0.json | 64 +++++++++ ...f_Input_Type_Via_Mutation_Body_NET9_0.json | 59 +++++++++ ...SelfRef_Output_Type_Via_Query_NET10_0.json | 54 ++++++++ ....SelfRef_Output_Type_Via_Query_NET9_0.json | 50 +++++++ .../test/Adapters.OpenApi.Tests/TestSchema.cs | 59 +++++++++ 16 files changed, 980 insertions(+), 116 deletions(-) create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET10_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET9_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET10_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET9_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET10_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET9_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET10_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET9_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET10_0.json create mode 100644 src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET9_0.json diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/OpenApiIntegrationTests.cs b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/OpenApiIntegrationTests.cs index 27da54a436e..064b66faaa1 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/OpenApiIntegrationTests.cs +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/OpenApiIntegrationTests.cs @@ -54,4 +54,128 @@ query GetUsers @http(method: GET, route: "/users") { // assert Assert.Contains("/users", document); } + + [Fact] + public async Task SelfRef_Input_Type_Via_Mutation_Body() + { + // arrange + var storage = new TestOpenApiDefinitionStorage( + """ + mutation SubmitSelfRef($input: SelfReferencingInput! @body) + @http(method: POST, route: "/self-ref") { + submitSelfRef(input: $input) + } + """); + var server = CreateTestServer(storage); + var client = server.CreateClient(); + + // act + var document = await GetOpenApiDocumentAsync(client); + + // assert + document.MatchSnapshot(postFix: TestEnvironment.TargetFramework, extension: ".json"); + } + + [Fact] + public async Task SelfRef_Output_Type_Via_Query() + { + // arrange + var storage = new TestOpenApiDefinitionStorage( + """ + query GetTree @http(method: GET, route: "/tree") { + tree { + value + children { + value + } + } + } + """); + var server = CreateTestServer(storage); + var client = server.CreateClient(); + + // act + var document = await GetOpenApiDocumentAsync(client); + + // assert + document.MatchSnapshot(postFix: TestEnvironment.TargetFramework, extension: ".json"); + } + + [Fact] + public async Task Indirect_Input_Type_Via_Mutation_Body() + { + // arrange + // A -> B -> A: the body inlines IndirectParentInput, then the cycle closes through + // the IndirectMiddleInput and IndirectParentInput components. + var storage = new TestOpenApiDefinitionStorage( + """ + mutation SubmitIndirect($input: IndirectParentInput! @body) + @http(method: POST, route: "/indirect-input") { + submitIndirect(input: $input) + } + """); + var server = CreateTestServer(storage); + var client = server.CreateClient(); + + // act + var document = await GetOpenApiDocumentAsync(client); + + // assert + document.MatchSnapshot(postFix: TestEnvironment.TargetFramework, extension: ".json"); + } + + [Fact] + public async Task Indirect_Output_Type_Via_Query() + { + // arrange + // A -> B -> A selected a couple of levels deep so the expansion is bounded by the + // selection set rather than the type cycle. + var storage = new TestOpenApiDefinitionStorage( + """ + query GetIndirect @http(method: GET, route: "/indirect-output") { + indirect { + value + middle { + label + parent { + value + middle { + label + } + } + } + } + } + """); + var server = CreateTestServer(storage); + var client = server.CreateClient(); + + // act + var document = await GetOpenApiDocumentAsync(client); + + // assert + document.MatchSnapshot(postFix: TestEnvironment.TargetFramework, extension: ".json"); + } + + [Fact] + public async Task Indirect_Input_Type_With_Two_Sibling_Occurrences() + { + // arrange + // The same input type appears at two sibling positions and both must emit a $ref. + var storage = new TestOpenApiDefinitionStorage( + """ + mutation SubmitTwoChildren($input: TwoChildrenInput! @body) + @http(method: POST, route: "/two-children") { + submitTwoChildren(input: $input) + } + """); + var server = CreateTestServer(storage); + var client = server.CreateClient(); + + // act + var document = await GetOpenApiDocumentAsync(client); + + // assert + document.MatchSnapshot(postFix: TestEnvironment.TargetFramework, extension: ".json"); + } } diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json index 147f37807b6..964b8dcbe37 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json @@ -184,35 +184,7 @@ "format": "int64" }, "object": { - "required": [ - "field1A" - ], - "type": "object", - "properties": { - "field1A": { - "required": [ - "field1B" - ], - "type": "object", - "properties": { - "field1B": { - "required": [ - "field1C" - ], - "type": "object", - "properties": { - "field1C": { - "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", - "type": "string", - "description": "field1C description" - } - }, - "description": "field1B description" - } - }, - "description": "field1A description" - } - } + "$ref": "#/components/schemas/Object1NonNullableInput" }, "short": { "type": "integer", @@ -1095,6 +1067,41 @@ }, "components": { "schemas": { + "Object1NonNullableInput": { + "required": [ + "field1A" + ], + "type": "object", + "properties": { + "field1A": { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + } + }, + "Object2NonNullableInput": { + "required": [ + "field1B" + ], + "type": "object", + "properties": { + "field1B": { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + } + }, + "Object3NonNullableInput": { + "required": [ + "field1C" + ], + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, "UserAddress": { "required": [ "street" diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json index 147f37807b6..964b8dcbe37 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json @@ -184,35 +184,7 @@ "format": "int64" }, "object": { - "required": [ - "field1A" - ], - "type": "object", - "properties": { - "field1A": { - "required": [ - "field1B" - ], - "type": "object", - "properties": { - "field1B": { - "required": [ - "field1C" - ], - "type": "object", - "properties": { - "field1C": { - "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", - "type": "string", - "description": "field1C description" - } - }, - "description": "field1B description" - } - }, - "description": "field1A description" - } - } + "$ref": "#/components/schemas/Object1NonNullableInput" }, "short": { "type": "integer", @@ -1095,6 +1067,41 @@ }, "components": { "schemas": { + "Object1NonNullableInput": { + "required": [ + "field1A" + ], + "type": "object", + "properties": { + "field1A": { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + } + }, + "Object2NonNullableInput": { + "required": [ + "field1B" + ], + "type": "object", + "properties": { + "field1B": { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + } + }, + "Object3NonNullableInput": { + "required": [ + "field1C" + ], + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, "UserAddress": { "required": [ "street" diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json index c431deaaec4..beadf2a3dcf 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json @@ -179,35 +179,7 @@ "format": "int64" }, "object": { - "required": [ - "field1A" - ], - "type": "object", - "properties": { - "field1A": { - "required": [ - "field1B" - ], - "type": "object", - "properties": { - "field1B": { - "required": [ - "field1C" - ], - "type": "object", - "properties": { - "field1C": { - "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", - "type": "string", - "description": "field1C description" - } - }, - "description": "field1B description" - } - }, - "description": "field1A description" - } - } + "$ref": "#/components/schemas/Object1NonNullableInput" }, "short": { "type": "integer", @@ -1044,6 +1016,41 @@ } }, "description": "The user's address" + }, + "Object3NonNullableInput": { + "required": [ + "field1C" + ], + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, + "Object2NonNullableInput": { + "required": [ + "field1B" + ], + "type": "object", + "properties": { + "field1B": { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + } + }, + "Object1NonNullableInput": { + "required": [ + "field1A" + ], + "type": "object", + "properties": { + "field1A": { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + } } } } diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json index c431deaaec4..beadf2a3dcf 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json @@ -179,35 +179,7 @@ "format": "int64" }, "object": { - "required": [ - "field1A" - ], - "type": "object", - "properties": { - "field1A": { - "required": [ - "field1B" - ], - "type": "object", - "properties": { - "field1B": { - "required": [ - "field1C" - ], - "type": "object", - "properties": { - "field1C": { - "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", - "type": "string", - "description": "field1C description" - } - }, - "description": "field1B description" - } - }, - "description": "field1A description" - } - } + "$ref": "#/components/schemas/Object1NonNullableInput" }, "short": { "type": "integer", @@ -1044,6 +1016,41 @@ } }, "description": "The user's address" + }, + "Object3NonNullableInput": { + "required": [ + "field1C" + ], + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, + "Object2NonNullableInput": { + "required": [ + "field1B" + ], + "type": "object", + "properties": { + "field1B": { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + } + }, + "Object1NonNullableInput": { + "required": [ + "field1A" + ], + "type": "object", + "properties": { + "field1A": { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + } } } } diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET10_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET10_0.json new file mode 100644 index 00000000000..2b43a6c2652 --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET10_0.json @@ -0,0 +1,75 @@ +{ + "openapi": "3.1.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost/" + } + ], + "paths": { + "/indirect-input": { + "post": { + "operationId": "submitIndirect", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "middle": { + "$ref": "#/components/schemas/IndirectMiddleInput" + }, + "name": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "IndirectMiddleInput": { + "type": "object", + "properties": { + "label": { + "type": "string" + }, + "parent": { + "$ref": "#/components/schemas/IndirectParentInput" + } + } + }, + "IndirectParentInput": { + "type": "object", + "properties": { + "middle": { + "$ref": "#/components/schemas/IndirectMiddleInput" + }, + "name": { + "type": "string" + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET9_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET9_0.json new file mode 100644 index 00000000000..af3ec2b9924 --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_Via_Mutation_Body_NET9_0.json @@ -0,0 +1,70 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "paths": { + "/indirect-input": { + "post": { + "operationId": "submitIndirect", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "middle": { + "$ref": "#/components/schemas/IndirectMiddleInput" + }, + "name": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "IndirectParentInput": { + "type": "object", + "properties": { + "middle": { + "$ref": "#/components/schemas/IndirectMiddleInput" + }, + "name": { + "type": "string" + } + } + }, + "IndirectMiddleInput": { + "type": "object", + "properties": { + "label": { + "type": "string" + }, + "parent": { + "$ref": "#/components/schemas/IndirectParentInput" + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET10_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET10_0.json new file mode 100644 index 00000000000..9cf7f1a4da3 --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET10_0.json @@ -0,0 +1,64 @@ +{ + "openapi": "3.1.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost/" + } + ], + "paths": { + "/two-children": { + "post": { + "operationId": "submitTwoChildren", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "left": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "right": { + "$ref": "#/components/schemas/SelfReferencingInput" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "SelfReferencingInput": { + "type": "object", + "properties": { + "child": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "value": { + "type": "string" + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET9_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET9_0.json new file mode 100644 index 00000000000..517ffa3c916 --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Input_Type_With_Two_Sibling_Occurrences_NET9_0.json @@ -0,0 +1,59 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "paths": { + "/two-children": { + "post": { + "operationId": "submitTwoChildren", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "left": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "right": { + "$ref": "#/components/schemas/SelfReferencingInput" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "SelfReferencingInput": { + "type": "object", + "properties": { + "child": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "value": { + "type": "string" + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET10_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET10_0.json new file mode 100644 index 00000000000..fef6cfbd0ea --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET10_0.json @@ -0,0 +1,84 @@ +{ + "openapi": "3.1.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost/" + } + ], + "paths": { + "/indirect-output": { + "get": { + "operationId": "getIndirect", + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "required": [ + "value", + "middle" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "middle": { + "required": [ + "label", + "parent" + ], + "type": [ + "null", + "object" + ], + "properties": { + "label": { + "type": "string" + }, + "parent": { + "required": [ + "value", + "middle" + ], + "type": [ + "null", + "object" + ], + "properties": { + "value": { + "type": "string" + }, + "middle": { + "required": [ + "label" + ], + "type": [ + "null", + "object" + ], + "properties": { + "label": { + "type": "string" + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET9_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET9_0.json new file mode 100644 index 00000000000..8956f7eeebf --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.Indirect_Output_Type_Via_Query_NET9_0.json @@ -0,0 +1,74 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "paths": { + "/indirect-output": { + "get": { + "operationId": "getIndirect", + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "required": [ + "value", + "middle" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "middle": { + "required": [ + "label", + "parent" + ], + "type": "object", + "properties": { + "label": { + "type": "string" + }, + "parent": { + "required": [ + "value", + "middle" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "middle": { + "required": [ + "label" + ], + "type": "object", + "properties": { + "label": { + "type": "string" + } + }, + "nullable": true + } + }, + "nullable": true + } + }, + "nullable": true + } + } + } + } + } + } + } + } + } + }, + "components": { } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET10_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET10_0.json new file mode 100644 index 00000000000..4ab42ba0946 --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET10_0.json @@ -0,0 +1,64 @@ +{ + "openapi": "3.1.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost/" + } + ], + "paths": { + "/self-ref": { + "post": { + "operationId": "submitSelfRef", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "child": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "value": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "SelfReferencingInput": { + "type": "object", + "properties": { + "child": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "value": { + "type": "string" + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET9_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET9_0.json new file mode 100644 index 00000000000..340c2221ad9 --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Input_Type_Via_Mutation_Body_NET9_0.json @@ -0,0 +1,59 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "paths": { + "/self-ref": { + "post": { + "operationId": "submitSelfRef", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "child": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "value": { + "type": "string" + } + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "SelfReferencingInput": { + "type": "object", + "properties": { + "child": { + "$ref": "#/components/schemas/SelfReferencingInput" + }, + "value": { + "type": "string" + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET10_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET10_0.json new file mode 100644 index 00000000000..299188f4bdf --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET10_0.json @@ -0,0 +1,54 @@ +{ + "openapi": "3.1.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "servers": [ + { + "url": "http://localhost/" + } + ], + "paths": { + "/tree": { + "get": { + "operationId": "getTree", + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "required": [ + "value", + "children" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "children": { + "type": "array", + "items": { + "required": [ + "value" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + } + } + } + } + } + } + } + } + } + } + } + } + } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET9_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET9_0.json new file mode 100644 index 00000000000..917253f92b1 --- /dev/null +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTests.SelfRef_Output_Type_Via_Query_NET9_0.json @@ -0,0 +1,50 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "HotChocolate.Adapters.OpenApi.Tests | v1", + "version": "1.0.0" + }, + "paths": { + "/tree": { + "get": { + "operationId": "getTree", + "responses": { + "200": { + "description": null, + "content": { + "application/json": { + "schema": { + "required": [ + "value", + "children" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "children": { + "type": "array", + "items": { + "required": [ + "value" + ], + "type": "object", + "properties": { + "value": { + "type": "string" + } + } + } + } + } + } + } + } + } + } + } + } + }, + "components": { } +} diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs index b951ee54432..68173c81760 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs @@ -101,6 +101,10 @@ public string SearchProducts(string? text, float? minPrice) public string SearchProductsPaginated(string? text, int first) => $"Searched for: {text ?? "all"}, first: {first}"; + + public TreeNode? GetTree() => null; + + public IndirectParentNode? GetIndirect() => null; } public class Mutation @@ -116,6 +120,61 @@ public User UpdateUser(UserInput user) } public DeeplyNested UpdateDeeplyNestedObject(DeeplyNested input) => input; + + public bool SubmitSelfRef(SelfReferencingInput input) => true; + + public bool SubmitIndirect(IndirectParentInput input) => true; + + public bool SubmitTwoChildren(TwoChildrenInput input) => true; + } + + public sealed class SelfReferencingInput + { + public string? Value { get; init; } + + public SelfReferencingInput? Child { get; init; } + } + + public sealed class IndirectParentInput + { + public string? Name { get; init; } + + public IndirectMiddleInput? Middle { get; init; } + } + + public sealed class IndirectMiddleInput + { + public string? Label { get; init; } + + public IndirectParentInput? Parent { get; init; } + } + + public sealed class TwoChildrenInput + { + public SelfReferencingInput? Left { get; init; } + + public SelfReferencingInput? Right { get; init; } + } + + public sealed class IndirectParentNode + { + public required string Value { get; init; } + + public IndirectMiddleNode? Middle { get; init; } + } + + public sealed class IndirectMiddleNode + { + public required string Label { get; init; } + + public IndirectParentNode? Parent { get; init; } + } + + public sealed class TreeNode + { + public required string Value { get; init; } + + public required List Children { get; init; } } public class DeeplyNested From a5b5a6020958704d639b0ac4f2735e0028b018c1 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Fri, 5 Jun 2026 11:54:26 +0200 Subject: [PATCH 2/4] wip: fix --- .../DynamicOpenApiDocumentTransformer.cs | 251 ++++++++++++++---- 1 file changed, 199 insertions(+), 52 deletions(-) diff --git a/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs b/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs index 9ff4f500b47..803cf438ba4 100644 --- a/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs +++ b/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs @@ -25,6 +25,7 @@ internal sealed class DynamicOpenApiDocumentTransformer : IOpenApiDocumentTransf { private List _endpoints = []; private List _models = []; + private List _inputComponents = []; public Task TransformAsync( OpenApiDocument document, @@ -41,6 +42,11 @@ public Task TransformAsync( AddComponent(document, component.SchemaName, component.Schema); } + foreach (var component in _inputComponents) + { + AddComponent(document, component.SchemaName, component.Schema); + } + return Task.CompletedTask; } @@ -53,12 +59,18 @@ public void AddDefinitions( var endpointDescriptors = new List(); var modelDescriptors = new List(); var operationIdUsages = new Dictionary(); + var inputComponentContext = new InputComponentContext(schema); foreach (var endpoint in endpoints) { try { - var endpointDescriptor = CreateEndpointDescriptor(endpoint, schema, modelsByName, operationIdUsages); + var endpointDescriptor = CreateEndpointDescriptor( + endpoint, + schema, + modelsByName, + operationIdUsages, + inputComponentContext); endpointDescriptors.Add(endpointDescriptor); } catch @@ -71,7 +83,8 @@ public void AddDefinitions( { try { - var modelDescriptor = CreateModelDescriptor(model, schema, modelsByName); + var modelDescriptor = + CreateModelDescriptor(model, schema, modelsByName, inputComponentContext); modelDescriptors.Add(modelDescriptor); } catch @@ -82,6 +95,9 @@ public void AddDefinitions( _endpoints = endpointDescriptors; _models = modelDescriptors; + _inputComponents = inputComponentContext.Components + .Select(kvp => new ModelDescriptor(kvp.Key, kvp.Value)) + .ToList(); } private const string JsonContentType = "application/json"; @@ -90,7 +106,8 @@ private static EndpointDescriptor CreateEndpointDescriptor( OpenApiEndpointDefinition endpoint, ISchemaDefinition schema, IDictionary modelsByName, - IDictionary operationIdUsages) + IDictionary operationIdUsages, + InputComponentContext inputComponentContext) { var operation = new OpenApiOperation { @@ -105,7 +122,12 @@ private static EndpointDescriptor CreateEndpointDescriptor( foreach (var routeParameter in endpoint.RouteParameters) { - var parameter = CreateOpenApiParameter(endpoint, routeParameter, ParameterLocation.Path, schema); + var parameter = CreateOpenApiParameter( + endpoint, + routeParameter, + ParameterLocation.Path, + schema, + inputComponentContext); operation.Parameters.Add(parameter); @@ -117,7 +139,12 @@ private static EndpointDescriptor CreateEndpointDescriptor( foreach (var queryParameter in endpoint.QueryParameters) { - var parameter = CreateOpenApiParameter(endpoint, queryParameter, ParameterLocation.Query, schema); + var parameter = CreateOpenApiParameter( + endpoint, + queryParameter, + ParameterLocation.Query, + schema, + inputComponentContext); operation.Parameters.Add(parameter); @@ -130,7 +157,23 @@ private static EndpointDescriptor CreateEndpointDescriptor( if (bodyVariableName is not null) { var (graphqlType, _) = GetBodyVariableDetails(endpoint.OperationDefinition, bodyVariableName, schema); - var requestBodyType = CreateOpenApiSchemaForType(graphqlType, schema); + + // Expanded inline (not a $ref) so RemovePropertiesFromSchema can strip fields + // bound to route or query parameters; a $ref has no inline properties to remove. + OpenApiSchemaAbstraction requestBodyType; + + if (graphqlType.NamedType() is IInputObjectTypeDefinition bodyInputObject + && !graphqlType.IsListType()) + { + requestBodyType = BuildInputObjectSchema( + bodyInputObject, + inputComponentContext, + bodyVariableTrie); + } + else + { + requestBodyType = CreateOpenApiSchemaForType(graphqlType, schema, inputComponentContext); + } RemovePropertiesFromSchema(requestBodyType, bodyVariableTrie); @@ -161,8 +204,9 @@ private static EndpointDescriptor CreateEndpointDescriptor( fieldType, schema, endpoint.LocalFragmentsByName, - modelsByName) - : CreateOpenApiSchemaForType(fieldType, schema); + modelsByName, + inputComponentContext) + : CreateOpenApiSchemaForType(fieldType, schema, inputComponentContext); var responseBody = new OpenApiMediaType { @@ -183,7 +227,8 @@ private static EndpointDescriptor CreateEndpointDescriptor( private static ModelDescriptor CreateModelDescriptor( OpenApiModelDefinition model, ISchemaDefinition schema, - IDictionary modelsByName) + IDictionary modelsByName, + InputComponentContext inputComponentContext) { if (!schema.Types.TryGetType(model.FragmentDefinition.TypeCondition.Name.Value, out var typeCondition)) @@ -196,7 +241,8 @@ private static ModelDescriptor CreateModelDescriptor( (IOutputType)typeCondition, schema, model.LocalFragmentsByName, - modelsByName); + modelsByName, + inputComponentContext); componentSchema.Description = model.Description; @@ -279,15 +325,17 @@ private static OperationType GetOperationType(string httpMethod) } #endif - private static OpenApiSchema CreateOpenApiSchemaForType( + private static OpenApiSchemaAbstraction CreateOpenApiSchemaForType( IType type, ISchemaDefinition schemaDefinition, + InputComponentContext inputComponentContext, IValueNode? defaultValue = null) { if (type.IsListType()) { var elementType = type.ElementType(); - OpenApiSchemaAbstraction itemSchema = CreateOpenApiSchemaForType(elementType, schemaDefinition); + var itemSchema = + CreateOpenApiSchemaForType(elementType, schemaDefinition, inputComponentContext); itemSchema = ApplyNullability(itemSchema, elementType); @@ -308,34 +356,7 @@ private static OpenApiSchema CreateOpenApiSchemaForType( if (namedType is IInputObjectTypeDefinition inputObject) { - var schema = CreateObjectSchema(defaultValue); - - foreach (var field in inputObject.Fields) - { - if (field.IsIntrospectionField) - { - continue; - } - - if (field.Type.IsNonNullType()) - { - schema.Required!.Add(field.Name); - } - - var fieldTypeSchema = CreateOpenApiSchemaForType(field.Type, schemaDefinition); - fieldTypeSchema.Deprecated = field.IsDeprecated; - - if (field.Description is not null) - { - fieldTypeSchema.Description = field.Description; - } - - schema.Properties!.Add(field.Name, fieldTypeSchema); - } - - schema.Description = inputObject.Description; - - return schema; + return RegisterInputType(inputObject, inputComponentContext); } if (namedType is IObjectTypeDefinition objectType) @@ -349,13 +370,10 @@ private static OpenApiSchema CreateOpenApiSchemaForType( continue; } - var fieldTypeSchema = CreateOpenApiSchemaForType(field.Type, schemaDefinition); - fieldTypeSchema.Deprecated = field.IsDeprecated; + var fieldTypeSchema = + CreateOpenApiSchemaForType(field.Type, schemaDefinition, inputComponentContext); - if (field.Description is not null) - { - fieldTypeSchema.Description = field.Description; - } + fieldTypeSchema = ApplyFieldMetadata(fieldTypeSchema, field.Description, field.IsDeprecated); schema.Properties!.Add(field.Name, ApplyNullability(fieldTypeSchema, field.Type)); } @@ -372,7 +390,8 @@ private static OpenApiSchema CreateOpenApiSchemaForType( foreach (var possibleType in possibleTypes) { - var typeSchema = CreateOpenApiSchemaForType(possibleType, schemaDefinition); + var typeSchema = + CreateOpenApiSchemaForType(possibleType, schemaDefinition, inputComponentContext); items.Add(typeSchema); } @@ -389,7 +408,8 @@ private static OpenApiSchema CreateOpenApiSchemaForType( foreach (var possibleType in unionType.Types) { - var typeSchema = CreateOpenApiSchemaForType(possibleType, schemaDefinition); + var typeSchema = + CreateOpenApiSchemaForType(possibleType, schemaDefinition, inputComponentContext); items.Add(typeSchema); } @@ -403,6 +423,117 @@ private static OpenApiSchema CreateOpenApiSchemaForType( throw new NotSupportedException(); } + private static OpenApiSchemaAbstraction RegisterInputType( + IInputObjectTypeDefinition inputObject, + InputComponentContext inputComponentContext) + { + var name = inputObject.Name; + + // Register the name before building so a self- or mutual-reference resolves to a $ref. + if (inputComponentContext.RegisteredNames.Add(name)) + { + var componentSchema = BuildInputObjectSchema(inputObject, inputComponentContext, trie: null); + inputComponentContext.Components[name] = componentSchema; + } + + return CreateSchemaReference(name); + } + + private static OpenApiSchema BuildInputObjectSchema( + IInputObjectTypeDefinition inputObject, + InputComponentContext inputComponentContext, + InputObjectPathTrie? trie) + { + var schema = CreateObjectSchema(); + + foreach (var field in inputObject.Fields) + { + if (field.IsIntrospectionField) + { + continue; + } + + if (field.Type.IsNonNullType()) + { + schema.Required!.Add(field.Name); + } + + OpenApiSchemaAbstraction fieldTypeSchema; + + if (trie is not null + && trie.TryGetValue(field.Name, out var childTrie) + && !childTrie.IsTerminal + && field.Type.NamedType() is IInputObjectTypeDefinition nestedInputObject + && !field.Type.IsListType()) + { + // A parameter is bound to a value nested in this field, so it must stay inline + // (not a shared $ref) so it can be stripped from this endpoint's body only. + fieldTypeSchema = BuildInputObjectSchema(nestedInputObject, inputComponentContext, childTrie); + } + else + { + fieldTypeSchema = CreateOpenApiSchemaForType( + field.Type, + inputComponentContext.Schema, + inputComponentContext); + } + + fieldTypeSchema = ApplyFieldMetadata(fieldTypeSchema, field.Description, field.IsDeprecated); + + schema.Properties!.Add(field.Name, fieldTypeSchema); + } + + schema.Description = inputObject.Description; + + return schema; + } + + private static OpenApiSchemaAbstraction ApplyFieldMetadata( + OpenApiSchemaAbstraction schema, + string? description, + bool isDeprecated) + { + // A $ref describes the referenced component, not the field, so it is returned unchanged. +#if NET10_0_OR_GREATER + if (schema is not OpenApiSchema concreteSchema) + { + return schema; + } +#else + if (schema.Reference is not null) + { + return schema; + } + + var concreteSchema = schema; +#endif + + concreteSchema.Deprecated = isDeprecated; + + if (description is not null) + { + concreteSchema.Description = description; + } + + return concreteSchema; + } + + private static OpenApiSchemaAbstraction CreateSchemaReference(string name) + { +#if NET10_0_OR_GREATER + return new OpenApiSchemaReference(name); +#else + return new OpenApiSchema + { + Reference = new OpenApiReference + { + Type = ReferenceType.Schema, + Id = name + } + }; +#endif + } + private static OpenApiSchema CreateOneOfSchema(IList schemas) { return new OpenApiSchema { OneOf = schemas }; @@ -743,6 +874,7 @@ private static OpenApiSchemaAbstraction CreateOpenApiSchemaForSelectionSet( ISchemaDefinition schemaDefinition, IDictionary localFragmentLookup, IDictionary modelsByName, + InputComponentContext inputComponentContext, bool optional = false) { if (typeDefinition.IsListType()) @@ -754,6 +886,7 @@ private static OpenApiSchemaAbstraction CreateOpenApiSchemaForSelectionSet( schemaDefinition, localFragmentLookup, modelsByName, + inputComponentContext, optional); itemSchema = ApplyNullability(itemSchema, elementType); @@ -787,11 +920,12 @@ private static OpenApiSchemaAbstraction CreateOpenApiSchemaForSelectionSet( fieldType, schemaDefinition, localFragmentLookup, - modelsByName); + modelsByName, + inputComponentContext); } else { - typeSchema = CreateOpenApiSchemaForType(fieldType, schemaDefinition); + typeSchema = CreateOpenApiSchemaForType(fieldType, schemaDefinition, inputComponentContext); } fieldSchema ??= CreateObjectSchema(); @@ -819,6 +953,7 @@ private static OpenApiSchemaAbstraction CreateOpenApiSchemaForSelectionSet( schemaDefinition, localFragmentLookup, modelsByName, + inputComponentContext, optional: optional || isDifferentType || isSelectionConditional); fragmentSchemasByType ??= []; @@ -875,6 +1010,7 @@ private static OpenApiSchemaAbstraction CreateOpenApiSchemaForSelectionSet( schemaDefinition, localFragmentLookup, modelsByName, + inputComponentContext, optional: optional || isDifferentType || isSelectionConditional); fragmentSchemasByType ??= []; @@ -955,7 +1091,8 @@ private static OpenApiParameter CreateOpenApiParameter( OpenApiEndpointDefinition endpoint, OpenApiEndpointDefinitionParameter parameter, ParameterLocation location, - ISchemaDefinition schema) + ISchemaDefinition schema, + InputComponentContext inputComponentContext) { var (graphqlType, defaultValue) = GetParameterDetails(endpoint.OperationDefinition, parameter, schema); @@ -964,7 +1101,7 @@ private static OpenApiParameter CreateOpenApiParameter( Name = parameter.Key, In = location, Required = graphqlType.IsNonNullType(), - Schema = CreateOpenApiSchemaForType(graphqlType, schema, defaultValue) + Schema = CreateOpenApiSchemaForType(graphqlType, schema, inputComponentContext, defaultValue) }; } @@ -1095,6 +1232,16 @@ private sealed record EndpointDescriptor(string Path, string HttpMethod, OpenApi private sealed record ModelDescriptor(string SchemaName, OpenApiSchemaAbstraction Schema); + // Shared across all endpoints so each input type is registered as a component once. + private sealed class InputComponentContext(ISchemaDefinition schema) + { + public ISchemaDefinition Schema { get; } = schema; + + public Dictionary Components { get; } = []; + + public HashSet RegisteredNames { get; } = []; + } + private sealed class InputObjectPathTrie : Dictionary { public bool IsTerminal { get; private set; } From 4e730b4ebfa5c87fe1d2e93010a486158891e8f1 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Fri, 5 Jun 2026 13:58:53 +0200 Subject: [PATCH 3/4] Refactor DynamicOpenApiDocumentTransformer --- .../DynamicOpenApiDocumentTransformer.cs | 1835 ++++++++--------- 1 file changed, 891 insertions(+), 944 deletions(-) diff --git a/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs b/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs index 803cf438ba4..9c8b34822a5 100644 --- a/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs +++ b/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs @@ -23,9 +23,11 @@ namespace HotChocolate.Adapters.OpenApi; internal sealed class DynamicOpenApiDocumentTransformer : IOpenApiDocumentTransformer, IDynamicOpenApiDocumentTransformer { + private const string JsonContentType = "application/json"; + private List _endpoints = []; - private List _models = []; - private List _inputComponents = []; + private List _models = []; + private List _inputComponents = []; public Task TransformAsync( OpenApiDocument document, @@ -56,197 +58,12 @@ public void AddDefinitions( IDictionary modelsByName, ISchemaDefinition schema) { - var endpointDescriptors = new List(); - var modelDescriptors = new List(); - var operationIdUsages = new Dictionary(); - var inputComponentContext = new InputComponentContext(schema); - - foreach (var endpoint in endpoints) - { - try - { - var endpointDescriptor = CreateEndpointDescriptor( - endpoint, - schema, - modelsByName, - operationIdUsages, - inputComponentContext); - endpointDescriptors.Add(endpointDescriptor); - } - catch - { - // If the construction of an endpoint descriptor fails, we just skip over it. - } - } - - foreach (var model in models) - { - try - { - var modelDescriptor = - CreateModelDescriptor(model, schema, modelsByName, inputComponentContext); - modelDescriptors.Add(modelDescriptor); - } - catch - { - // If the construction of an model descriptor fails, we just skip over it. - } - } + var (endpointDescriptors, modelDescriptors, inputComponents) = + new DocumentBuilder(schema, modelsByName).Build(endpoints, models); _endpoints = endpointDescriptors; _models = modelDescriptors; - _inputComponents = inputComponentContext.Components - .Select(kvp => new ModelDescriptor(kvp.Key, kvp.Value)) - .ToList(); - } - - private const string JsonContentType = "application/json"; - - private static EndpointDescriptor CreateEndpointDescriptor( - OpenApiEndpointDefinition endpoint, - ISchemaDefinition schema, - IDictionary modelsByName, - IDictionary operationIdUsages, - InputComponentContext inputComponentContext) - { - var operation = new OpenApiOperation - { - Description = endpoint.Description, - OperationId = CreateOperationId(endpoint.OperationDefinition.Name?.Value, operationIdUsages), - Parameters = [], - Responses = [] - }; - - var bodyVariableName = endpoint.BodyVariableName; - var bodyVariableTrie = new InputObjectPathTrie(); - - foreach (var routeParameter in endpoint.RouteParameters) - { - var parameter = CreateOpenApiParameter( - endpoint, - routeParameter, - ParameterLocation.Path, - schema, - inputComponentContext); - - operation.Parameters.Add(parameter); - - if (routeParameter.VariableName == bodyVariableName && routeParameter.InputObjectPath is not null) - { - bodyVariableTrie.Add(routeParameter); - } - } - - foreach (var queryParameter in endpoint.QueryParameters) - { - var parameter = CreateOpenApiParameter( - endpoint, - queryParameter, - ParameterLocation.Query, - schema, - inputComponentContext); - - operation.Parameters.Add(parameter); - - if (queryParameter.VariableName == bodyVariableName && queryParameter.InputObjectPath is not null) - { - bodyVariableTrie.Add(queryParameter); - } - } - - if (bodyVariableName is not null) - { - var (graphqlType, _) = GetBodyVariableDetails(endpoint.OperationDefinition, bodyVariableName, schema); - - // Expanded inline (not a $ref) so RemovePropertiesFromSchema can strip fields - // bound to route or query parameters; a $ref has no inline properties to remove. - OpenApiSchemaAbstraction requestBodyType; - - if (graphqlType.NamedType() is IInputObjectTypeDefinition bodyInputObject - && !graphqlType.IsListType()) - { - requestBodyType = BuildInputObjectSchema( - bodyInputObject, - inputComponentContext, - bodyVariableTrie); - } - else - { - requestBodyType = CreateOpenApiSchemaForType(graphqlType, schema, inputComponentContext); - } - - RemovePropertiesFromSchema(requestBodyType, bodyVariableTrie); - - var requestBody = new OpenApiRequestBody - { - Required = true, - Content = new Dictionary - { - [JsonContentType] = new() { Schema = requestBodyType } - } - }; - - operation.RequestBody = requestBody; - } - - var operationType = schema.GetOperationType(endpoint.OperationDefinition.Operation); - - if (endpoint.OperationDefinition.SelectionSet.Selections is not [FieldNode rootField]) - { - throw new InvalidOperationException("Expected to have a single field selection on the root"); - } - - var fieldType = operationType.Fields[rootField.Name.Value].Type; - - var responseSchema = rootField.SelectionSet is not null - ? CreateOpenApiSchemaForSelectionSet( - rootField.SelectionSet, - fieldType, - schema, - endpoint.LocalFragmentsByName, - modelsByName, - inputComponentContext) - : CreateOpenApiSchemaForType(fieldType, schema, inputComponentContext); - - var responseBody = new OpenApiMediaType - { - Schema = responseSchema - }; - - operation.Responses["200"] = new OpenApiResponse - { - Content = new ConcurrentDictionary { [JsonContentType] = responseBody } - }; - - return new EndpointDescriptor( - endpoint.Route, - endpoint.HttpMethod, - operation); - } - - private static ModelDescriptor CreateModelDescriptor( - OpenApiModelDefinition model, - ISchemaDefinition schema, - IDictionary modelsByName, - InputComponentContext inputComponentContext) - { - if (!schema.Types.TryGetType(model.FragmentDefinition.TypeCondition.Name.Value, - out var typeCondition)) - { - throw new InvalidOperationException("Expected to find type condition type in the schema."); - } - - var componentSchema = CreateOpenApiSchemaForSelectionSet( - model.FragmentDefinition.SelectionSet, - (IOutputType)typeCondition, - schema, - model.LocalFragmentsByName, - modelsByName, - inputComponentContext); - - componentSchema.Description = model.Description; - - return new ModelDescriptor(model.Name, componentSchema); + _inputComponents = inputComponents; } private static void AddComponent( @@ -325,1026 +142,1156 @@ private static OperationType GetOperationType(string httpMethod) } #endif - private static OpenApiSchemaAbstraction CreateOpenApiSchemaForType( - IType type, - ISchemaDefinition schemaDefinition, - InputComponentContext inputComponentContext, - IValueNode? defaultValue = null) + private sealed record EndpointDescriptor(string Path, string HttpMethod, OpenApiOperation Operation); + + private sealed record ComponentDescriptor(string SchemaName, OpenApiSchemaAbstraction Schema); + + private sealed class InputObjectPathTrie : Dictionary { - if (type.IsListType()) - { - var elementType = type.ElementType(); - var itemSchema = - CreateOpenApiSchemaForType(elementType, schemaDefinition, inputComponentContext); + public bool IsTerminal { get; private set; } - itemSchema = ApplyNullability(itemSchema, elementType); + public void Add(OpenApiEndpointDefinitionParameter parameter) + { + if (parameter.InputObjectPath is not { } inputObjectPath || inputObjectPath.Length == 0) + { + return; + } - return CreateArraySchema(itemSchema, defaultValue); - } + var currentNode = this; - var namedType = type.NamedType(); + foreach (var segment in inputObjectPath) + { + if (!currentNode.TryGetValue(segment, out var nextNode)) + { + nextNode = new InputObjectPathTrie(); + currentNode[segment] = nextNode; + } - if (namedType is IScalarTypeDefinition scalarType) - { - return CreateScalarSchema(scalarType, defaultValue); - } + currentNode = nextNode; + } - if (namedType is IEnumTypeDefinition enumType) - { - return CreateEnumSchema(enumType, defaultValue); + currentNode.IsTerminal = true; } + } - if (namedType is IInputObjectTypeDefinition inputObject) - { - return RegisterInputType(inputObject, inputComponentContext); - } + // Owns the per-build state so each input type is registered as a component once and + // ambient values (schema, models) are read from fields instead of threaded as parameters. + private sealed class DocumentBuilder( + ISchemaDefinition schema, + IDictionary modelsByName) + { + private readonly ISchemaDefinition _schema = schema; + private readonly IDictionary _modelsByName = modelsByName; + private readonly Dictionary _operationIdUsages = []; + private readonly Dictionary _inputComponents = []; + private readonly HashSet _registeredInputNames = []; - if (namedType is IObjectTypeDefinition objectType) + public (List Endpoints, List Models, List InputComponents) + Build(OpenApiEndpointDefinition[] endpoints, OpenApiModelDefinition[] models) { - var schema = CreateObjectSchema(); + var endpointDescriptors = new List(); + var modelDescriptors = new List(); - foreach (var field in objectType.Fields) + foreach (var endpoint in endpoints) { - if (field.IsIntrospectionField) + try { - continue; + var endpointDescriptor = CreateEndpointDescriptor(endpoint); + endpointDescriptors.Add(endpointDescriptor); } + catch + { + // If the construction of an endpoint descriptor fails, we just skip over it. + } + } - var fieldTypeSchema = - CreateOpenApiSchemaForType(field.Type, schemaDefinition, inputComponentContext); - - fieldTypeSchema = ApplyFieldMetadata(fieldTypeSchema, field.Description, field.IsDeprecated); - - schema.Properties!.Add(field.Name, ApplyNullability(fieldTypeSchema, field.Type)); + foreach (var model in models) + { + try + { + var modelDescriptor = CreateModelDescriptor(model); + modelDescriptors.Add(modelDescriptor); + } + catch + { + // If the construction of an model descriptor fails, we just skip over it. + } } - schema.Description = objectType.Description; + var inputComponents = _inputComponents + .Select(kvp => new ComponentDescriptor(kvp.Key, kvp.Value)) + .ToList(); - return schema; + return (endpointDescriptors, modelDescriptors, inputComponents); } - if (namedType is IInterfaceTypeDefinition interfaceType) + private EndpointDescriptor CreateEndpointDescriptor(OpenApiEndpointDefinition endpoint) { - var possibleTypes = schemaDefinition.GetPossibleTypes(interfaceType); - var items = new List(); - - foreach (var possibleType in possibleTypes) + var operation = new OpenApiOperation { - var typeSchema = - CreateOpenApiSchemaForType(possibleType, schemaDefinition, inputComponentContext); + Description = endpoint.Description, + OperationId = CreateOperationId(endpoint.OperationDefinition.Name?.Value), + Parameters = [], + Responses = [] + }; - items.Add(typeSchema); - } + var bodyVariableName = endpoint.BodyVariableName; + var bodyVariableTrie = new InputObjectPathTrie(); - var schema = CreateOneOfSchema(items); - schema.Description = interfaceType.Description; + foreach (var routeParameter in endpoint.RouteParameters) + { + var parameter = CreateOpenApiParameter(endpoint, routeParameter, ParameterLocation.Path); - return schema; - } + operation.Parameters.Add(parameter); - if (namedType is IUnionTypeDefinition unionType) - { - var items = new List(); + if (routeParameter.VariableName == bodyVariableName && routeParameter.InputObjectPath is not null) + { + bodyVariableTrie.Add(routeParameter); + } + } - foreach (var possibleType in unionType.Types) + foreach (var queryParameter in endpoint.QueryParameters) { - var typeSchema = - CreateOpenApiSchemaForType(possibleType, schemaDefinition, inputComponentContext); + var parameter = CreateOpenApiParameter(endpoint, queryParameter, ParameterLocation.Query); - items.Add(typeSchema); + operation.Parameters.Add(parameter); + + if (queryParameter.VariableName == bodyVariableName && queryParameter.InputObjectPath is not null) + { + bodyVariableTrie.Add(queryParameter); + } } - var schema = CreateOneOfSchema(items); - schema.Description = unionType.Description; + if (bodyVariableName is not null) + { + var (graphqlType, _) = GetBodyVariableDetails(endpoint.OperationDefinition, bodyVariableName); - return schema; - } + // Expanded inline (not a $ref) so RemovePropertiesFromSchema can strip fields + // bound to route or query parameters; a $ref has no inline properties to remove. + OpenApiSchemaAbstraction requestBodyType; - throw new NotSupportedException(); - } + if (graphqlType.NamedType() is IInputObjectTypeDefinition bodyInputObject + && !graphqlType.IsListType()) + { + requestBodyType = BuildInputObjectSchema(bodyInputObject, bodyVariableTrie); + } + else + { + requestBodyType = CreateOpenApiSchemaForType(graphqlType); + } - private static OpenApiSchemaAbstraction RegisterInputType( - IInputObjectTypeDefinition inputObject, - InputComponentContext inputComponentContext) - { - var name = inputObject.Name; + RemovePropertiesFromSchema(requestBodyType, bodyVariableTrie); - // Register the name before building so a self- or mutual-reference resolves to a $ref. - if (inputComponentContext.RegisteredNames.Add(name)) - { - var componentSchema = BuildInputObjectSchema(inputObject, inputComponentContext, trie: null); - inputComponentContext.Components[name] = componentSchema; - } + var requestBody = new OpenApiRequestBody + { + Required = true, + Content = new Dictionary + { + [JsonContentType] = new() { Schema = requestBodyType } + } + }; - return CreateSchemaReference(name); - } + operation.RequestBody = requestBody; + } - private static OpenApiSchema BuildInputObjectSchema( - IInputObjectTypeDefinition inputObject, - InputComponentContext inputComponentContext, - InputObjectPathTrie? trie) - { - var schema = CreateObjectSchema(); + var operationType = _schema.GetOperationType(endpoint.OperationDefinition.Operation); - foreach (var field in inputObject.Fields) - { - if (field.IsIntrospectionField) + if (endpoint.OperationDefinition.SelectionSet.Selections is not [FieldNode rootField]) { - continue; + throw new InvalidOperationException("Expected to have a single field selection on the root"); } - if (field.Type.IsNonNullType()) - { - schema.Required!.Add(field.Name); - } + var fieldType = operationType.Fields[rootField.Name.Value].Type; - OpenApiSchemaAbstraction fieldTypeSchema; + var responseSchema = rootField.SelectionSet is not null + ? CreateOpenApiSchemaForSelectionSet( + rootField.SelectionSet, + fieldType, + endpoint.LocalFragmentsByName) + : CreateOpenApiSchemaForType(fieldType); - if (trie is not null - && trie.TryGetValue(field.Name, out var childTrie) - && !childTrie.IsTerminal - && field.Type.NamedType() is IInputObjectTypeDefinition nestedInputObject - && !field.Type.IsListType()) - { - // A parameter is bound to a value nested in this field, so it must stay inline - // (not a shared $ref) so it can be stripped from this endpoint's body only. - fieldTypeSchema = BuildInputObjectSchema(nestedInputObject, inputComponentContext, childTrie); - } - else + var responseBody = new OpenApiMediaType { - fieldTypeSchema = CreateOpenApiSchemaForType( - field.Type, - inputComponentContext.Schema, - inputComponentContext); - } + Schema = responseSchema + }; - fieldTypeSchema = ApplyFieldMetadata(fieldTypeSchema, field.Description, field.IsDeprecated); + operation.Responses["200"] = new OpenApiResponse + { + Content = new ConcurrentDictionary { [JsonContentType] = responseBody } + }; - schema.Properties!.Add(field.Name, fieldTypeSchema); + return new EndpointDescriptor( + endpoint.Route, + endpoint.HttpMethod, + operation); } - schema.Description = inputObject.Description; + private ComponentDescriptor CreateModelDescriptor(OpenApiModelDefinition model) + { + if (!_schema.Types.TryGetType(model.FragmentDefinition.TypeCondition.Name.Value, + out var typeCondition)) + { + throw new InvalidOperationException("Expected to find type condition type in the schema."); + } - return schema; - } + var componentSchema = CreateOpenApiSchemaForSelectionSet( + model.FragmentDefinition.SelectionSet, + (IOutputType)typeCondition, + model.LocalFragmentsByName); - private static OpenApiSchemaAbstraction ApplyFieldMetadata( - OpenApiSchemaAbstraction schema, - string? description, - bool isDeprecated) - { - // A $ref describes the referenced component, not the field, so it is returned unchanged. -#if NET10_0_OR_GREATER - if (schema is not OpenApiSchema concreteSchema) - { - return schema; + componentSchema.Description = model.Description; + + return new ComponentDescriptor(model.Name, componentSchema); } -#else - if (schema.Reference is not null) + + private OpenApiSchemaAbstraction CreateOpenApiSchemaForType( + IType type, + IValueNode? defaultValue = null) { - return schema; - } + if (type.IsListType()) + { + var elementType = type.ElementType(); + var itemSchema = CreateOpenApiSchemaForType(elementType); - var concreteSchema = schema; -#endif + itemSchema = ApplyNullability(itemSchema, elementType); - concreteSchema.Deprecated = isDeprecated; + return CreateArraySchema(itemSchema, defaultValue); + } - if (description is not null) - { - concreteSchema.Description = description; - } + var namedType = type.NamedType(); - return concreteSchema; - } + if (namedType is IScalarTypeDefinition scalarType) + { + return CreateScalarSchema(scalarType, defaultValue); + } - private static OpenApiSchemaAbstraction CreateSchemaReference(string name) - { -#if NET10_0_OR_GREATER - return new OpenApiSchemaReference(name); -#else - return new OpenApiSchema - { - Reference = new OpenApiReference + if (namedType is IEnumTypeDefinition enumType) { - Type = ReferenceType.Schema, - Id = name + return CreateEnumSchema(enumType, defaultValue); } - }; -#endif - } - private static OpenApiSchema CreateOneOfSchema(IList schemas) - { - return new OpenApiSchema { OneOf = schemas }; - } + if (namedType is IInputObjectTypeDefinition inputObject) + { + return RegisterInputType(inputObject); + } - private static OpenApiSchema CreateAllOfSchema(IList schemas) - { - return new OpenApiSchema { AllOf = schemas }; - } + if (namedType is IObjectTypeDefinition objectType) + { + var schema = CreateObjectSchema(); - private static OpenApiSchema CreateObjectSchema(IValueNode? defaultValue = null) - { - var schema = new OpenApiSchema(); + foreach (var field in objectType.Fields) + { + if (field.IsIntrospectionField) + { + continue; + } -#if NET10_0_OR_GREATER - schema.Type = JsonSchemaType.Object; -#else - schema.Type = "object"; -#endif - schema.Properties = new Dictionary(); - schema.Required = new HashSet(); + var fieldTypeSchema = CreateOpenApiSchemaForType(field.Type); - if (defaultValue is not null) - { - schema.Default = GetOpenApiValue(defaultValue); - } + fieldTypeSchema = ApplyFieldMetadata(fieldTypeSchema, field.Description, field.IsDeprecated); - return schema; - } + schema.Properties!.Add(field.Name, ApplyNullability(fieldTypeSchema, field.Type)); + } - private static OpenApiSchema CreateArraySchema(OpenApiSchemaAbstraction itemSchema, IValueNode? defaultValue) - { - var schema = new OpenApiSchema(); -#if NET10_0_OR_GREATER - schema.Type = JsonSchemaType.Array; -#else - schema.Type = "array"; -#endif - schema.Items = itemSchema; + schema.Description = objectType.Description; - if (defaultValue is not null) - { - schema.Default = GetOpenApiValue(defaultValue); - } + return schema; + } - return schema; - } + if (namedType is IInterfaceTypeDefinition interfaceType) + { + var possibleTypes = _schema.GetPossibleTypes(interfaceType); + var items = new List(); - private static OpenApiSchema CreateEnumSchema(IEnumTypeDefinition enumType, IValueNode? defaultValue) - { - var schema = new OpenApiSchema { Description = enumType.Description }; + foreach (var possibleType in possibleTypes) + { + var typeSchema = CreateOpenApiSchemaForType(possibleType); -#if NET10_0_OR_GREATER - schema.Type = JsonSchemaType.String; - schema.Enum = enumType.Values.Select(JsonNode (v) => JsonValue.Create(v.Name)).ToList(); -#else - schema.Type = "string"; - schema.Enum = enumType.Values.Select(IOpenApiAny (v) => new OpenApiString(v.Name)).ToList(); -#endif + items.Add(typeSchema); + } - if (defaultValue is not null) - { - schema.Default = GetOpenApiValue(defaultValue); - } + var schema = CreateOneOfSchema(items); + schema.Description = interfaceType.Description; - return schema; - } + return schema; + } - private static OpenApiSchema CreateScalarSchema(IScalarTypeDefinition scalarType, IValueNode? defaultValue) - { - var schema = new OpenApiSchema(); + if (namedType is IUnionTypeDefinition unionType) + { + var items = new List(); - if (scalarType.Name is not "ID" and not "String" and not "Int" and not "Float" and not "Boolean") - { - schema.Description = scalarType.Description; - } + foreach (var possibleType in unionType.Types) + { + var typeSchema = CreateOpenApiSchemaForType(possibleType); -#if NET10_0_OR_GREATER - var jsonSchemaTypes = GetJsonSchemaTypes(scalarType); + items.Add(typeSchema); + } - if (jsonSchemaTypes.Count == 1) - { - schema.Type = jsonSchemaTypes[0]; + var schema = CreateOneOfSchema(items); + schema.Description = unionType.Description; - if (schema.Type == JsonSchemaType.String && !string.IsNullOrEmpty(scalarType.Pattern)) - { - schema.Pattern = scalarType.Pattern; + return schema; } + + throw new NotSupportedException(); } - else - { - schema.OneOf = jsonSchemaTypes - .ConvertAll(OpenApiSchemaAbstraction (t) => new OpenApiSchema { Type = t }); - } -#else - var jsonSchemaTypes = GetJsonSchemaTypes(scalarType); - if (jsonSchemaTypes.Count == 1) + private OpenApiSchemaAbstraction RegisterInputType(IInputObjectTypeDefinition inputObject) { - schema.Type = jsonSchemaTypes[0]; + var name = inputObject.Name; - if (schema.Type == "string" && !string.IsNullOrEmpty(scalarType.Pattern)) + // Register the name before building so a self- or mutual-reference resolves to a $ref. + if (_registeredInputNames.Add(name)) { - schema.Pattern = scalarType.Pattern; + var componentSchema = BuildInputObjectSchema(inputObject, trie: null); + _inputComponents[name] = componentSchema; } - } - else - { - schema.OneOf = jsonSchemaTypes - .Select(t => new OpenApiSchema { Type = t }) - .ToList(); - } -#endif - schema.Format = GetJsonSchemaFormat(scalarType); - schema.Pattern = GetJsonSchemaPattern(scalarType); + return CreateSchemaReference(name); + } - if (defaultValue is not null) + private OpenApiSchema BuildInputObjectSchema( + IInputObjectTypeDefinition inputObject, + InputObjectPathTrie? trie) { - schema.Default = GetOpenApiValue(defaultValue); - } + var schema = CreateObjectSchema(); - return schema; - } + foreach (var field in inputObject.Fields) + { + if (field.IsIntrospectionField) + { + continue; + } - private static string? GetJsonSchemaFormat(IScalarTypeDefinition scalarType) - { - var format = scalarType.Name switch - { - SpecScalarNames.Float.Name => "double", - SpecScalarNames.Int.Name => "int32", - _ => null - }; + if (field.Type.IsNonNullType()) + { + schema.Required!.Add(field.Name); + } - return format ?? scalarType.SpecifiedBy?.OriginalString switch - { - "https://scalars.graphql.org/chillicream/byte.html" => "int8", - "https://scalars.graphql.org/chillicream/date-time.html" => "date-time", - "https://scalars.graphql.org/chillicream/date.html" => "date", - "https://scalars.graphql.org/chillicream/duration.html" => "duration", - "https://scalars.graphql.org/chillicream/local-date.html" => "date", - "https://scalars.graphql.org/chillicream/long.html" => "int64", - "https://scalars.graphql.org/chillicream/short.html" => "int16", - "https://scalars.graphql.org/chillicream/unsigned-byte.html" => "uint8", - "https://scalars.graphql.org/chillicream/unsigned-int.html" => "uint32", - "https://scalars.graphql.org/chillicream/unsigned-long.html" => "uint64", - "https://scalars.graphql.org/chillicream/unsigned-short.html" => "uint16", - "https://scalars.graphql.org/chillicream/uri.html" => "uri", - "https://scalars.graphql.org/chillicream/url.html" => "uri", - "https://scalars.graphql.org/chillicream/uuid.html" => "uuid", - _ => null - }; - } + OpenApiSchemaAbstraction fieldTypeSchema; - private static string? GetJsonSchemaPattern(IScalarTypeDefinition scalarType) - { - var pattern = scalarType.SpecifiedBy?.OriginalString switch - { - "https://scalars.graphql.org/chillicream/base64-string.html" - => @"^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$", - "https://scalars.graphql.org/chillicream/date.html" - => @"^\d{4}-\d{2}-\d{2}$", - "https://scalars.graphql.org/chillicream/date-time.html" - => @"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:[Zz]|[+-]\d{2}:\d{2})$", - "https://scalars.graphql.org/chillicream/duration.html" - => @"^-?P(?:\d+W|(?=\d|T(?:\d|$))(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?)$", - "https://scalars.graphql.org/chillicream/local-date.html" - => @"^\d{4}-\d{2}-\d{2}$", - "https://scalars.graphql.org/chillicream/local-date-time.html" - => @"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?$", - "https://scalars.graphql.org/chillicream/local-time.html" - => @"^\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?$", - "https://scalars.graphql.org/chillicream/uuid.html" - => @"^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$", - _ => null - }; + if (trie is not null + && trie.TryGetValue(field.Name, out var childTrie) + && !childTrie.IsTerminal + && field.Type.NamedType() is IInputObjectTypeDefinition nestedInputObject + && !field.Type.IsListType()) + { + // A parameter is bound to a value nested in this field, so it must stay inline + // (not a shared $ref) so it can be stripped from this endpoint's body only. + fieldTypeSchema = BuildInputObjectSchema(nestedInputObject, childTrie); + } + else + { + fieldTypeSchema = CreateOpenApiSchemaForType(field.Type); + } - return pattern ?? scalarType.Pattern; - } + fieldTypeSchema = ApplyFieldMetadata(fieldTypeSchema, field.Description, field.IsDeprecated); -#if NET10_0_OR_GREATER - private static List GetJsonSchemaTypes(IScalarTypeDefinition scalarType) - { - var serializationType = scalarType.GetScalarSerializationType(); + schema.Properties!.Add(field.Name, fieldTypeSchema); + } - var possibleTypes = new List(); + schema.Description = inputObject.Description; - if (serializationType.HasFlag(ScalarSerializationType.String)) - { - possibleTypes.Add(JsonSchemaType.String); + return schema; } - if (serializationType.HasFlag(ScalarSerializationType.Boolean)) + private OpenApiSchemaAbstraction CreateOpenApiSchemaForSelectionSet( + SelectionSetNode selectionSet, + IOutputType typeDefinition, + IDictionary localFragmentLookup, + bool optional = false) { - possibleTypes.Add(JsonSchemaType.Boolean); - } + if (typeDefinition.IsListType()) + { + var elementType = (IOutputType)typeDefinition.ElementType(); + var itemSchema = CreateOpenApiSchemaForSelectionSet( + selectionSet, + elementType, + localFragmentLookup, + optional); - if (serializationType.HasFlag(ScalarSerializationType.Int)) - { - possibleTypes.Add(JsonSchemaType.Integer); - } + itemSchema = ApplyNullability(itemSchema, elementType); - if (serializationType.HasFlag(ScalarSerializationType.Float)) - { - possibleTypes.Add(JsonSchemaType.Number); - } + return CreateArraySchema(itemSchema, null); + } - if (serializationType.HasFlag(ScalarSerializationType.Object)) - { - possibleTypes.Add(JsonSchemaType.Object); - } + var namedType = typeDefinition.NamedType(); - if (serializationType.HasFlag(ScalarSerializationType.List)) - { - possibleTypes.Add(JsonSchemaType.Array); - } + OpenApiSchema? fieldSchema = null; + Dictionary>? fragmentSchemasByType = null; - if (possibleTypes.Count > 0) - { - return possibleTypes; - } + foreach (var selection in selectionSet.Selections) + { + var isSelectionConditional = IsConditional(selection); - return [JsonSchemaType.String]; - } -#else - private static List GetJsonSchemaTypes(IScalarTypeDefinition scalarType) - { - var serializationType = scalarType.GetScalarSerializationType(); + if (selection is FieldNode field) + { + var fieldName = field.Name.Value; + var responseName = field.Alias?.Value ?? fieldName; - var possibleTypes = new List(); + var fieldType = fieldName == IntrospectionFieldNames.TypeName ? + new NonNullType(_schema.Types["String"]) : + ((IComplexTypeDefinition)namedType).Fields[fieldName].Type; - if (serializationType.HasFlag(ScalarSerializationType.String)) - { - possibleTypes.Add("string"); - } + OpenApiSchemaAbstraction typeSchema; + if (field.SelectionSet is not null) + { + typeSchema = CreateOpenApiSchemaForSelectionSet( + field.SelectionSet, + fieldType, + localFragmentLookup); + } + else + { + typeSchema = CreateOpenApiSchemaForType(fieldType); + } - if (serializationType.HasFlag(ScalarSerializationType.Boolean)) - { - possibleTypes.Add("boolean"); - } + fieldSchema ??= CreateObjectSchema(); - if (serializationType.HasFlag(ScalarSerializationType.Int)) - { - possibleTypes.Add("integer"); - } + if (!optional && !isSelectionConditional) + { + fieldSchema.Required!.Add(responseName); + } - if (serializationType.HasFlag(ScalarSerializationType.Float)) - { - possibleTypes.Add("number"); - } + typeSchema = ApplyNullability(typeSchema, fieldType); - if (serializationType.HasFlag(ScalarSerializationType.Object)) - { - possibleTypes.Add("object"); - } + fieldSchema.Properties!.TryAdd(responseName, typeSchema); + } + else if (selection is InlineFragmentNode inlineFragment) + { + var typeCondition = inlineFragment.TypeCondition is null + ? namedType + : _schema.Types[inlineFragment.TypeCondition.Name.Value]; + var isDifferentType = !typeCondition.IsAssignableFrom(namedType); + var typeName = typeCondition.Name; - if (serializationType.HasFlag(ScalarSerializationType.List)) - { - possibleTypes.Add("array"); - } + var typeConditionSchema = CreateOpenApiSchemaForSelectionSet( + inlineFragment.SelectionSet, + (IOutputType)typeCondition, + localFragmentLookup, + optional: optional || isDifferentType || isSelectionConditional); - if (possibleTypes.Count > 0) - { - return possibleTypes; - } + fragmentSchemasByType ??= []; - return ["string"]; - } -#endif + if (!fragmentSchemasByType.TryGetValue(typeName, out var schemaList)) + { + schemaList = []; + fragmentSchemasByType[typeName] = schemaList; + } + + schemaList.Add(typeConditionSchema); + } + else if (selection is FragmentSpreadNode fragmentSpread) + { + var fragmentName = fragmentSpread.Name.Value; + + if (_modelsByName.TryGetValue(fragmentName, out var externalFragment)) + { + var typeName = externalFragment.FragmentDefinition.TypeCondition.Name.Value; + + fragmentSchemasByType ??= []; + + if (!fragmentSchemasByType.TryGetValue(typeName, out var schemaList)) + { + schemaList = []; + fragmentSchemasByType[typeName] = schemaList; + } #if NET10_0_OR_GREATER - private static JsonNode? GetOpenApiValue(IValueNode value) - { - return value switch - { - StringValueNode stringValue => JsonValue.Create(stringValue.Value), - IntValueNode intValue => JsonValue.Create(intValue.ToInt64()), - FloatValueNode floatValue => JsonValue.Create(floatValue.ToDouble()), - BooleanValueNode boolValue => JsonValue.Create(boolValue.Value), - EnumValueNode enumValue => JsonValue.Create(enumValue.Value), - NullValueNode => null, - ListValueNode listValue => new JsonArray(listValue.Items.Select(GetOpenApiValue).ToArray()), - ObjectValueNode objectValue => new JsonObject( - objectValue.Fields.Select(f => - new KeyValuePair(f.Name.Value, GetOpenApiValue(f.Value)))), - _ => null - }; - } + schemaList.Add(new OpenApiSchemaReference(fragmentName)); #else - private static IOpenApiAny? GetOpenApiValue(IValueNode value) - { - return value switch - { - StringValueNode stringValue => new OpenApiString(stringValue.Value), - IntValueNode intValue => new OpenApiLong(intValue.ToInt64()), - FloatValueNode floatValue => new OpenApiDouble(floatValue.ToDouble()), - BooleanValueNode boolValue => new OpenApiBoolean(boolValue.Value), - EnumValueNode enumValue => new OpenApiString(enumValue.Value), - NullValueNode => new OpenApiNull(), - ListValueNode listValue => ToOpenApiArray(listValue), - ObjectValueNode objectValue => ToOpenApiObject(objectValue), - _ => null - }; - } + var externalReference = new OpenApiSchema + { + Reference = new OpenApiReference + { + Type = ReferenceType.Schema, + Id = fragmentName + } + }; + + schemaList.Add(externalReference); +#endif + } + else + { + var fragment = localFragmentLookup[fragmentName]; + var typeCondition = _schema.Types[fragment.TypeCondition.Name.Value]; + var isDifferentType = !typeCondition.IsAssignableFrom(namedType); + var typeName = typeCondition.Name; - private static OpenApiArray ToOpenApiArray(ListValueNode listValue) - { - var array = new OpenApiArray(); - foreach (var item in listValue.Items) - { - var value = GetOpenApiValue(item); - if (value is not null) - { - array.Add(value); + var typeConditionSchema = CreateOpenApiSchemaForSelectionSet( + fragment.SelectionSet, + (IOutputType)typeCondition, + localFragmentLookup, + optional: optional || isDifferentType || isSelectionConditional); + + fragmentSchemasByType ??= []; + + if (!fragmentSchemasByType.TryGetValue(typeName, out var schemaList)) + { + schemaList = []; + fragmentSchemasByType[typeName] = schemaList; + } + + schemaList.Add(typeConditionSchema); + } + } } - } - return array; - } - private static OpenApiObject ToOpenApiObject(ObjectValueNode objectValue) - { - var obj = new OpenApiObject(); - foreach (var field in objectValue.Fields) - { - var value = GetOpenApiValue(field.Value); - if (value is not null) + // Build fragment schemas - one entry per type (using allOf to combine multiple fragments on same type) + var fragmentSchemas = fragmentSchemasByType? + .Select(kvp => kvp.Value.Count == 1 ? kvp.Value[0] : CreateAllOfSchema(kvp.Value)) + .ToList(); + + // Determine the final schema based on what we have + return (fieldSchema, fragmentSchemas) switch { - obj[field.Name.Value] = value; - } - } - return obj; - } -#endif + // Only field schema, no fragments + (not null, null or { Count: 0 }) => fieldSchema, - private static OpenApiSchemaAbstraction CreateOpenApiSchemaForSelectionSet( - SelectionSetNode selectionSet, - IOutputType typeDefinition, - ISchemaDefinition schemaDefinition, - IDictionary localFragmentLookup, - IDictionary modelsByName, - InputComponentContext inputComponentContext, - bool optional = false) - { - if (typeDefinition.IsListType()) - { - var elementType = (IOutputType)typeDefinition.ElementType(); - var itemSchema = CreateOpenApiSchemaForSelectionSet( - selectionSet, - elementType, - schemaDefinition, - localFragmentLookup, - modelsByName, - inputComponentContext, - optional); - - itemSchema = ApplyNullability(itemSchema, elementType); - - return CreateArraySchema(itemSchema, null); - } + // Only one fragment schema, no field schema + (null, { Count: 1 }) => fragmentSchemas[0], + + // Multiple fragment schemas (oneOf), no field schema + (null, { Count: > 1 }) => CreateOneOfSchema(fragmentSchemas), + + // Field schema + multiple fragment schemas (allOf with oneOf) + (not null, { Count: > 1 }) => CreateAllOfSchema([fieldSchema, CreateOneOfSchema(fragmentSchemas)]), - var namedType = typeDefinition.NamedType(); + // Field schema + single fragment schema (allOf) + (not null, { Count: 1 }) => CreateAllOfSchema([fieldSchema, fragmentSchemas[0]]), - OpenApiSchema? fieldSchema = null; - Dictionary>? fragmentSchemasByType = null; + // Should not happen, but handle gracefully + _ => CreateObjectSchema() + }; + } - foreach (var selection in selectionSet.Selections) + private OpenApiParameter CreateOpenApiParameter( + OpenApiEndpointDefinition endpoint, + OpenApiEndpointDefinitionParameter parameter, + ParameterLocation location) { - var isSelectionConditional = IsConditional(selection); + var (graphqlType, defaultValue) = GetParameterDetails(endpoint.OperationDefinition, parameter); - if (selection is FieldNode field) + return new OpenApiParameter { - var fieldName = field.Name.Value; - var responseName = field.Alias?.Value ?? fieldName; + Name = parameter.Key, + In = location, + Required = graphqlType.IsNonNullType(), + Schema = CreateOpenApiSchemaForType(graphqlType, defaultValue) + }; + } - var fieldType = fieldName == IntrospectionFieldNames.TypeName ? - new NonNullType(schemaDefinition.Types["String"]) : - ((IComplexTypeDefinition)namedType).Fields[fieldName].Type; + private (IType Type, IValueNode? DefaultValue) GetParameterDetails( + OperationDefinitionNode operation, + OpenApiEndpointDefinitionParameter parameter) + { + var variable = operation.VariableDefinitions + .FirstOrDefault(v => v.Variable.Name.Value == parameter.VariableName); - OpenApiSchemaAbstraction typeSchema; - if (field.SelectionSet is not null) - { - typeSchema = CreateOpenApiSchemaForSelectionSet( - field.SelectionSet, - fieldType, - schemaDefinition, - localFragmentLookup, - modelsByName, - inputComponentContext); - } - else - { - typeSchema = CreateOpenApiSchemaForType(fieldType, schemaDefinition, inputComponentContext); - } + if (variable is null) + { + throw new InvalidOperationException($"Expected to find variable named '{parameter.VariableName}'."); + } - fieldSchema ??= CreateObjectSchema(); + var namedVariableType = variable.Type.NamedType().Name.Value; - if (!optional && !isSelectionConditional) + if (!_schema.Types.TryGetType(variable.Type, out var variableType)) + { + throw new InvalidOperationException($"Expected to find type '{namedVariableType}'."); + } + + if (parameter.InputObjectPath is not { } inputObjectPath) + { + if (variable.DefaultValue is { } defaultValue) { - fieldSchema.Required!.Add(responseName); + return (variableType.NullableType(), defaultValue); } - typeSchema = ApplyNullability(typeSchema, fieldType); - - fieldSchema.Properties!.TryAdd(responseName, typeSchema); + return (variableType, null); } - else if (selection is InlineFragmentNode inlineFragment) - { - var typeCondition = inlineFragment.TypeCondition is null - ? namedType - : schemaDefinition.Types[inlineFragment.TypeCondition.Name.Value]; - var isDifferentType = !typeCondition.IsAssignableFrom(namedType); - var typeName = typeCondition.Name; - var typeConditionSchema = CreateOpenApiSchemaForSelectionSet( - inlineFragment.SelectionSet, - (IOutputType)typeCondition, - schemaDefinition, - localFragmentLookup, - modelsByName, - inputComponentContext, - optional: optional || isDifferentType || isSelectionConditional); + var currentType = variableType.NamedType(); + IInputValueDefinition? lastField = null; - fragmentSchemasByType ??= []; + foreach (var segment in inputObjectPath) + { + if (currentType is not IInputObjectTypeDefinition inputObject) + { + throw new InvalidOperationException($"Expected '{currentType.Name}' to be an input object type."); + } - if (!fragmentSchemasByType.TryGetValue(typeName, out var schemaList)) + if (!inputObject.Fields.TryGetField(segment, out lastField)) { - schemaList = []; - fragmentSchemasByType[typeName] = schemaList; + throw new InvalidOperationException( + $"Expected type '{currentType.Name}' to have a field named '{segment}'."); } - schemaList.Add(typeConditionSchema); + currentType = lastField.Type.NamedType(); } - else if (selection is FragmentSpreadNode fragmentSpread) - { - var fragmentName = fragmentSpread.Name.Value; - - if (modelsByName.TryGetValue(fragmentName, out var externalFragment)) - { - var typeName = externalFragment.FragmentDefinition.TypeCondition.Name.Value; - fragmentSchemasByType ??= []; + if (lastField is null) + { + throw new InvalidOperationException("Expected to resolve an input field through the inputObjectPath"); + } - if (!fragmentSchemasByType.TryGetValue(typeName, out var schemaList)) - { - schemaList = []; - fragmentSchemasByType[typeName] = schemaList; - } + if (lastField.DefaultValue is { } inputFieldDefaultValue) + { + return (lastField.Type.NullableType(), inputFieldDefaultValue); + } -#if NET10_0_OR_GREATER - schemaList.Add(new OpenApiSchemaReference(fragmentName)); -#else - var externalReference = new OpenApiSchema - { - Reference = new OpenApiReference - { - Type = ReferenceType.Schema, - Id = fragmentName - } - }; + return (lastField.Type, null); + } - schemaList.Add(externalReference); -#endif - } - else - { - var fragment = localFragmentLookup[fragmentName]; - var typeCondition = schemaDefinition.Types[fragment.TypeCondition.Name.Value]; - var isDifferentType = !typeCondition.IsAssignableFrom(namedType); - var typeName = typeCondition.Name; + private (IType Type, IValueNode? DefaultValue) GetBodyVariableDetails( + OperationDefinitionNode operation, + string variableName) + { + var variable = operation.VariableDefinitions + .FirstOrDefault(v => v.Variable.Name.Value == variableName); - var typeConditionSchema = CreateOpenApiSchemaForSelectionSet( - fragment.SelectionSet, - (IOutputType)typeCondition, - schemaDefinition, - localFragmentLookup, - modelsByName, - inputComponentContext, - optional: optional || isDifferentType || isSelectionConditional); + if (variable is null) + { + throw new InvalidOperationException($"Expected to find variable named '{variableName}'."); + } - fragmentSchemasByType ??= []; + var namedVariableType = variable.Type.NamedType().Name.Value; - if (!fragmentSchemasByType.TryGetValue(typeName, out var schemaList)) - { - schemaList = []; - fragmentSchemasByType[typeName] = schemaList; - } + if (!_schema.Types.TryGetType(variable.Type, out var variableType)) + { + throw new InvalidOperationException($"Expected to find type '{namedVariableType}'."); + } - schemaList.Add(typeConditionSchema); - } + if (variable.DefaultValue is { } defaultValue) + { + return (variableType.NullableType(), defaultValue); } - } - // Build fragment schemas - one entry per type (using allOf to combine multiple fragments on same type) - var fragmentSchemas = fragmentSchemasByType? - .Select(kvp => kvp.Value.Count == 1 ? kvp.Value[0] : CreateAllOfSchema(kvp.Value)) - .ToList(); + return (variableType, null); + } - // Determine the final schema based on what we have - return (fieldSchema, fragmentSchemas) switch + private string CreateOperationId(string? operationName) { - // Only field schema, no fragments - (not null, null or { Count: 0 }) => fieldSchema, + var operationId = GetOperationId(operationName); - // Only one fragment schema, no field schema - (null, { Count: 1 }) => fragmentSchemas[0], - - // Multiple fragment schemas (oneOf), no field schema - (null, { Count: > 1 }) => CreateOneOfSchema(fragmentSchemas), + if (!_operationIdUsages.TryGetValue(operationId, out var usage)) + { + _operationIdUsages[operationId] = 0; - // Field schema + multiple fragment schemas (allOf with oneOf) - (not null, { Count: > 1 }) => CreateAllOfSchema([fieldSchema, CreateOneOfSchema(fragmentSchemas)]), + return operationId; + } - // Field schema + single fragment schema (allOf) - (not null, { Count: 1 }) => CreateAllOfSchema([fieldSchema, fragmentSchemas[0]]), + usage++; + _operationIdUsages[operationId] = usage; - // Should not happen, but handle gracefully - _ => CreateObjectSchema() - }; - } + return $"{operationId}_{usage}"; + } - private static OpenApiSchemaAbstraction ApplyNullability(OpenApiSchemaAbstraction schema, IType type) - { - if (!type.IsNonNullType()) + private static OpenApiSchemaAbstraction ApplyFieldMetadata( + OpenApiSchemaAbstraction schema, + string? description, + bool isDeprecated) { + // A $ref describes the referenced component, not the field, so it is returned unchanged. #if NET10_0_OR_GREATER - if (schema is OpenApiSchemaReference schemaReference) - { - return CreateAllOfSchema([ - schemaReference, - new OpenApiSchema { Type = JsonSchemaType.Null } - ]); - } - - if (schema is OpenApiSchema objectSchema) + if (schema is not OpenApiSchema concreteSchema) { - objectSchema.Type |= JsonSchemaType.Null; + return schema; } #else if (schema.Reference is not null) { - return CreateAllOfSchema([ - schema, - new OpenApiSchema { Type = "null" } - ]); + return schema; } - schema.Nullable = true; + var concreteSchema = schema; #endif - } - return schema; - } + concreteSchema.Deprecated = isDeprecated; - private static OpenApiParameter CreateOpenApiParameter( - OpenApiEndpointDefinition endpoint, - OpenApiEndpointDefinitionParameter parameter, - ParameterLocation location, - ISchemaDefinition schema, - InputComponentContext inputComponentContext) - { - var (graphqlType, defaultValue) = GetParameterDetails(endpoint.OperationDefinition, parameter, schema); + if (description is not null) + { + concreteSchema.Description = description; + } - return new OpenApiParameter - { - Name = parameter.Key, - In = location, - Required = graphqlType.IsNonNullType(), - Schema = CreateOpenApiSchemaForType(graphqlType, schema, inputComponentContext, defaultValue) - }; - } + return concreteSchema; + } - private static bool IsConditional(ISelectionNode selection) - { - if (selection is FieldNode field) + private static OpenApiSchemaAbstraction CreateSchemaReference(string name) { - return HasConditionalDirective(field.Directives); +#if NET10_0_OR_GREATER + return new OpenApiSchemaReference(name); +#else + return new OpenApiSchema + { + Reference = new OpenApiReference + { + Type = ReferenceType.Schema, + Id = name + } + }; +#endif } - if (selection is InlineFragmentNode inlineFragment) + private static OpenApiSchema CreateOneOfSchema(IList schemas) { - return HasConditionalDirective(inlineFragment.Directives); + return new OpenApiSchema { OneOf = schemas }; } - if (selection is FragmentSpreadNode fragmentSpread) + private static OpenApiSchema CreateAllOfSchema(IList schemas) { - return HasConditionalDirective(fragmentSpread.Directives); + return new OpenApiSchema { AllOf = schemas }; } - return false; - } - - private static bool HasConditionalDirective(IReadOnlyList directives) - { - foreach (var directive in directives) + private static OpenApiSchema CreateObjectSchema(IValueNode? defaultValue = null) { - if (directive.Name.Value is "skip" or "include") + var schema = new OpenApiSchema(); + +#if NET10_0_OR_GREATER + schema.Type = JsonSchemaType.Object; +#else + schema.Type = "object"; +#endif + schema.Properties = new Dictionary(); + schema.Required = new HashSet(); + + if (defaultValue is not null) { - return true; + schema.Default = GetOpenApiValue(defaultValue); } + + return schema; } - return false; - } + private static OpenApiSchema CreateArraySchema(OpenApiSchemaAbstraction itemSchema, IValueNode? defaultValue) + { + var schema = new OpenApiSchema(); +#if NET10_0_OR_GREATER + schema.Type = JsonSchemaType.Array; +#else + schema.Type = "array"; +#endif + schema.Items = itemSchema; - private static (IType Type, IValueNode? DefaultValue) GetParameterDetails( - OperationDefinitionNode operation, - OpenApiEndpointDefinitionParameter parameter, - ISchemaDefinition schema) - { - var variable = operation.VariableDefinitions - .FirstOrDefault(v => v.Variable.Name.Value == parameter.VariableName); + if (defaultValue is not null) + { + schema.Default = GetOpenApiValue(defaultValue); + } - if (variable is null) - { - throw new InvalidOperationException($"Expected to find variable named '{parameter.VariableName}'."); + return schema; } - var namedVariableType = variable.Type.NamedType().Name.Value; - - if (!schema.Types.TryGetType(variable.Type, out var variableType)) + private static OpenApiSchema CreateEnumSchema(IEnumTypeDefinition enumType, IValueNode? defaultValue) { - throw new InvalidOperationException($"Expected to find type '{namedVariableType}'."); + var schema = new OpenApiSchema { Description = enumType.Description }; + +#if NET10_0_OR_GREATER + schema.Type = JsonSchemaType.String; + schema.Enum = enumType.Values.Select(JsonNode (v) => JsonValue.Create(v.Name)).ToList(); +#else + schema.Type = "string"; + schema.Enum = enumType.Values.Select(IOpenApiAny (v) => new OpenApiString(v.Name)).ToList(); +#endif + + if (defaultValue is not null) + { + schema.Default = GetOpenApiValue(defaultValue); + } + + return schema; } - if (parameter.InputObjectPath is not { } inputObjectPath) + private static OpenApiSchema CreateScalarSchema(IScalarTypeDefinition scalarType, IValueNode? defaultValue) { - if (variable.DefaultValue is { } defaultValue) + var schema = new OpenApiSchema(); + + if (scalarType.Name is not "ID" and not "String" and not "Int" and not "Float" and not "Boolean") { - return (variableType.NullableType(), defaultValue); + schema.Description = scalarType.Description; } - return (variableType, null); - } +#if NET10_0_OR_GREATER + var jsonSchemaTypes = GetJsonSchemaTypes(scalarType); - var currentType = variableType.NamedType(); - IInputValueDefinition? lastField = null; + if (jsonSchemaTypes.Count == 1) + { + schema.Type = jsonSchemaTypes[0]; - foreach (var segment in inputObjectPath) - { - if (currentType is not IInputObjectTypeDefinition inputObject) + if (schema.Type == JsonSchemaType.String && !string.IsNullOrEmpty(scalarType.Pattern)) + { + schema.Pattern = scalarType.Pattern; + } + } + else { - throw new InvalidOperationException($"Expected '{currentType.Name}' to be an input object type."); + schema.OneOf = jsonSchemaTypes + .ConvertAll(OpenApiSchemaAbstraction (t) => new OpenApiSchema { Type = t }); } +#else + var jsonSchemaTypes = GetJsonSchemaTypes(scalarType); + + if (jsonSchemaTypes.Count == 1) + { + schema.Type = jsonSchemaTypes[0]; + + if (schema.Type == "string" && !string.IsNullOrEmpty(scalarType.Pattern)) + { + schema.Pattern = scalarType.Pattern; + } + } + else + { + schema.OneOf = jsonSchemaTypes + .Select(t => new OpenApiSchema { Type = t }) + .ToList(); + } +#endif - if (!inputObject.Fields.TryGetField(segment, out lastField)) + schema.Format = GetJsonSchemaFormat(scalarType); + schema.Pattern = GetJsonSchemaPattern(scalarType); + + if (defaultValue is not null) { - throw new InvalidOperationException( - $"Expected type '{currentType.Name}' to have a field named '{segment}'."); + schema.Default = GetOpenApiValue(defaultValue); } - currentType = lastField.Type.NamedType(); + return schema; } - if (lastField is null) + private static string? GetJsonSchemaFormat(IScalarTypeDefinition scalarType) { - throw new InvalidOperationException("Expected to resolve an input field through the inputObjectPath"); + var format = scalarType.Name switch + { + SpecScalarNames.Float.Name => "double", + SpecScalarNames.Int.Name => "int32", + _ => null + }; + + return format ?? scalarType.SpecifiedBy?.OriginalString switch + { + "https://scalars.graphql.org/chillicream/byte.html" => "int8", + "https://scalars.graphql.org/chillicream/date-time.html" => "date-time", + "https://scalars.graphql.org/chillicream/date.html" => "date", + "https://scalars.graphql.org/chillicream/duration.html" => "duration", + "https://scalars.graphql.org/chillicream/local-date.html" => "date", + "https://scalars.graphql.org/chillicream/long.html" => "int64", + "https://scalars.graphql.org/chillicream/short.html" => "int16", + "https://scalars.graphql.org/chillicream/unsigned-byte.html" => "uint8", + "https://scalars.graphql.org/chillicream/unsigned-int.html" => "uint32", + "https://scalars.graphql.org/chillicream/unsigned-long.html" => "uint64", + "https://scalars.graphql.org/chillicream/unsigned-short.html" => "uint16", + "https://scalars.graphql.org/chillicream/uri.html" => "uri", + "https://scalars.graphql.org/chillicream/url.html" => "uri", + "https://scalars.graphql.org/chillicream/uuid.html" => "uuid", + _ => null + }; } - if (lastField.DefaultValue is { } inputFieldDefaultValue) + private static string? GetJsonSchemaPattern(IScalarTypeDefinition scalarType) { - return (lastField.Type.NullableType(), inputFieldDefaultValue); + var pattern = scalarType.SpecifiedBy?.OriginalString switch + { + "https://scalars.graphql.org/chillicream/base64-string.html" + => @"^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$", + "https://scalars.graphql.org/chillicream/date.html" + => @"^\d{4}-\d{2}-\d{2}$", + "https://scalars.graphql.org/chillicream/date-time.html" + => @"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:[Zz]|[+-]\d{2}:\d{2})$", + "https://scalars.graphql.org/chillicream/duration.html" + => @"^-?P(?:\d+W|(?=\d|T(?:\d|$))(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?)$", + "https://scalars.graphql.org/chillicream/local-date.html" + => @"^\d{4}-\d{2}-\d{2}$", + "https://scalars.graphql.org/chillicream/local-date-time.html" + => @"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?$", + "https://scalars.graphql.org/chillicream/local-time.html" + => @"^\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?$", + "https://scalars.graphql.org/chillicream/uuid.html" + => @"^[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$", + _ => null + }; + + return pattern ?? scalarType.Pattern; } - return (lastField.Type, null); - } +#if NET10_0_OR_GREATER + private static List GetJsonSchemaTypes(IScalarTypeDefinition scalarType) + { + var serializationType = scalarType.GetScalarSerializationType(); - private static (IType Type, IValueNode? DefaultValue) GetBodyVariableDetails( - OperationDefinitionNode operation, - string variableName, - ISchemaDefinition schema) - { - var variable = operation.VariableDefinitions - .FirstOrDefault(v => v.Variable.Name.Value == variableName); + var possibleTypes = new List(); - if (variable is null) - { - throw new InvalidOperationException($"Expected to find variable named '{variableName}'."); - } + if (serializationType.HasFlag(ScalarSerializationType.String)) + { + possibleTypes.Add(JsonSchemaType.String); + } - var namedVariableType = variable.Type.NamedType().Name.Value; + if (serializationType.HasFlag(ScalarSerializationType.Boolean)) + { + possibleTypes.Add(JsonSchemaType.Boolean); + } - if (!schema.Types.TryGetType(variable.Type, out var variableType)) - { - throw new InvalidOperationException($"Expected to find type '{namedVariableType}'."); - } + if (serializationType.HasFlag(ScalarSerializationType.Int)) + { + possibleTypes.Add(JsonSchemaType.Integer); + } - if (variable.DefaultValue is { } defaultValue) - { - return (variableType.NullableType(), defaultValue); - } + if (serializationType.HasFlag(ScalarSerializationType.Float)) + { + possibleTypes.Add(JsonSchemaType.Number); + } - return (variableType, null); - } + if (serializationType.HasFlag(ScalarSerializationType.Object)) + { + possibleTypes.Add(JsonSchemaType.Object); + } - private sealed record EndpointDescriptor(string Path, string HttpMethod, OpenApiOperation Operation); + if (serializationType.HasFlag(ScalarSerializationType.List)) + { + possibleTypes.Add(JsonSchemaType.Array); + } - private sealed record ModelDescriptor(string SchemaName, OpenApiSchemaAbstraction Schema); + if (possibleTypes.Count > 0) + { + return possibleTypes; + } - // Shared across all endpoints so each input type is registered as a component once. - private sealed class InputComponentContext(ISchemaDefinition schema) - { - public ISchemaDefinition Schema { get; } = schema; + return [JsonSchemaType.String]; + } +#else + private static List GetJsonSchemaTypes(IScalarTypeDefinition scalarType) + { + var serializationType = scalarType.GetScalarSerializationType(); - public Dictionary Components { get; } = []; + var possibleTypes = new List(); - public HashSet RegisteredNames { get; } = []; - } + if (serializationType.HasFlag(ScalarSerializationType.String)) + { + possibleTypes.Add("string"); + } - private sealed class InputObjectPathTrie : Dictionary - { - public bool IsTerminal { get; private set; } + if (serializationType.HasFlag(ScalarSerializationType.Boolean)) + { + possibleTypes.Add("boolean"); + } - public void Add(OpenApiEndpointDefinitionParameter parameter) - { - if (parameter.InputObjectPath is not { } inputObjectPath || inputObjectPath.Length == 0) + if (serializationType.HasFlag(ScalarSerializationType.Int)) { - return; + possibleTypes.Add("integer"); } - var currentNode = this; + if (serializationType.HasFlag(ScalarSerializationType.Float)) + { + possibleTypes.Add("number"); + } - foreach (var segment in inputObjectPath) + if (serializationType.HasFlag(ScalarSerializationType.Object)) { - if (!currentNode.TryGetValue(segment, out var nextNode)) - { - nextNode = new InputObjectPathTrie(); - currentNode[segment] = nextNode; - } + possibleTypes.Add("object"); + } - currentNode = nextNode; + if (serializationType.HasFlag(ScalarSerializationType.List)) + { + possibleTypes.Add("array"); } - currentNode.IsTerminal = true; + if (possibleTypes.Count > 0) + { + return possibleTypes; + } + + return ["string"]; } - } +#endif - private static void RemovePropertiesFromSchema( - OpenApiSchemaAbstraction schema, - InputObjectPathTrie trie) - { - if (schema.Properties == null || schema.Properties.Count == 0) +#if NET10_0_OR_GREATER + private static JsonNode? GetOpenApiValue(IValueNode value) { - return; + return value switch + { + StringValueNode stringValue => JsonValue.Create(stringValue.Value), + IntValueNode intValue => JsonValue.Create(intValue.ToInt64()), + FloatValueNode floatValue => JsonValue.Create(floatValue.ToDouble()), + BooleanValueNode boolValue => JsonValue.Create(boolValue.Value), + EnumValueNode enumValue => JsonValue.Create(enumValue.Value), + NullValueNode => null, + ListValueNode listValue => new JsonArray(listValue.Items.Select(GetOpenApiValue).ToArray()), + ObjectValueNode objectValue => new JsonObject( + objectValue.Fields.Select(f => + new KeyValuePair(f.Name.Value, GetOpenApiValue(f.Value)))), + _ => null + }; + } +#else + private static IOpenApiAny? GetOpenApiValue(IValueNode value) + { + return value switch + { + StringValueNode stringValue => new OpenApiString(stringValue.Value), + IntValueNode intValue => new OpenApiLong(intValue.ToInt64()), + FloatValueNode floatValue => new OpenApiDouble(floatValue.ToDouble()), + BooleanValueNode boolValue => new OpenApiBoolean(boolValue.Value), + EnumValueNode enumValue => new OpenApiString(enumValue.Value), + NullValueNode => new OpenApiNull(), + ListValueNode listValue => ToOpenApiArray(listValue), + ObjectValueNode objectValue => ToOpenApiObject(objectValue), + _ => null + }; } - var propertiesToRemove = new List(); - - foreach (var (propertyName, propertySchema) in schema.Properties) + private static OpenApiArray ToOpenApiArray(ListValueNode listValue) { - if (!trie.TryGetValue(propertyName, out var childTrie)) + var array = new OpenApiArray(); + foreach (var item in listValue.Items) { - continue; + var value = GetOpenApiValue(item); + if (value is not null) + { + array.Add(value); + } } + return array; + } - if (childTrie.IsTerminal) + private static OpenApiObject ToOpenApiObject(ObjectValueNode objectValue) + { + var obj = new OpenApiObject(); + foreach (var field in objectValue.Fields) { - propertiesToRemove.Add(propertyName); + var value = GetOpenApiValue(field.Value); + if (value is not null) + { + obj[field.Name.Value] = value; + } } - else if (childTrie.Count > 0 && propertySchema.Properties != null) + return obj; + } +#endif + + private static OpenApiSchemaAbstraction ApplyNullability(OpenApiSchemaAbstraction schema, IType type) + { + if (!type.IsNonNullType()) { - RemovePropertiesFromSchema(propertySchema, childTrie); +#if NET10_0_OR_GREATER + if (schema is OpenApiSchemaReference schemaReference) + { + return CreateAllOfSchema([ + schemaReference, + new OpenApiSchema { Type = JsonSchemaType.Null } + ]); + } + + if (schema is OpenApiSchema objectSchema) + { + objectSchema.Type |= JsonSchemaType.Null; + } +#else + if (schema.Reference is not null) + { + return CreateAllOfSchema([ + schema, + new OpenApiSchema { Type = "null" } + ]); + } + + schema.Nullable = true; +#endif } + + return schema; } - foreach (var propertyName in propertiesToRemove) + private static bool IsConditional(ISelectionNode selection) { - schema.Properties.Remove(propertyName); + if (selection is FieldNode field) + { + return HasConditionalDirective(field.Directives); + } + + if (selection is InlineFragmentNode inlineFragment) + { + return HasConditionalDirective(inlineFragment.Directives); + } + + if (selection is FragmentSpreadNode fragmentSpread) + { + return HasConditionalDirective(fragmentSpread.Directives); + } + + return false; } - if (schema.Required != null) + private static bool HasConditionalDirective(IReadOnlyList directives) { - foreach (var propertyName in propertiesToRemove) + foreach (var directive in directives) { - schema.Required.Remove(propertyName); + if (directive.Name.Value is "skip" or "include") + { + return true; + } } - } - } - private static string CreateOperationId(string? operationName, IDictionary usages) - { - var operationId = GetOperationId(operationName); + return false; + } - if (!usages.TryGetValue(operationId, out var usage)) + private static void RemovePropertiesFromSchema( + OpenApiSchemaAbstraction schema, + InputObjectPathTrie trie) { - usages[operationId] = 0; + if (schema.Properties == null || schema.Properties.Count == 0) + { + return; + } - return operationId; - } + var propertiesToRemove = new List(); - usage++; - usages[operationId] = usage; + foreach (var (propertyName, propertySchema) in schema.Properties) + { + if (!trie.TryGetValue(propertyName, out var childTrie)) + { + continue; + } - return $"{operationId}_{usage}"; - } + if (childTrie.IsTerminal) + { + propertiesToRemove.Add(propertyName); + } + else if (childTrie.Count > 0 && propertySchema.Properties != null) + { + RemovePropertiesFromSchema(propertySchema, childTrie); + } + } - private static string GetOperationId(string? operationName) - { - if (string.IsNullOrEmpty(operationName)) - { - return "unknown"; - } + foreach (var propertyName in propertiesToRemove) + { + schema.Properties.Remove(propertyName); + } - if (char.IsLower(operationName[0])) - { - return operationName; + if (schema.Required != null) + { + foreach (var propertyName in propertiesToRemove) + { + schema.Required.Remove(propertyName); + } + } } - return string.Create(operationName.Length, operationName, (span, str) => + private static string GetOperationId(string? operationName) { - str.AsSpan().CopyTo(span); - span[0] = char.ToLowerInvariant(span[0]); - }); + if (string.IsNullOrEmpty(operationName)) + { + return "unknown"; + } + + if (char.IsLower(operationName[0])) + { + return operationName; + } + + return string.Create(operationName.Length, operationName, (span, str) => + { + str.AsSpan().CopyTo(span); + span[0] = char.ToLowerInvariant(span[0]); + }); + } } } From 1b520a3e7638f4080510ad8bdac6f9f3a3ee5f29 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Mon, 8 Jun 2026 10:00:07 +0200 Subject: [PATCH 4/4] Fix descriptions/deprecated dropped from inputs --- .../DynamicOpenApiDocumentTransformer.cs | 24 +++---- ...enApi_Includes_Initial_Routes_NET10_0.json | 66 ++++++++++++++++++- ...ncludes_Initial_Routes_NET10_0_Fusion.json | 66 ++++++++++++++++++- ...penApi_Includes_Initial_Routes_NET9_0.json | 66 ++++++++++++++++++- ...Includes_Initial_Routes_NET9_0_Fusion.json | 66 ++++++++++++++++++- .../test/Adapters.OpenApi.Tests/TestSchema.cs | 8 ++- 6 files changed, 275 insertions(+), 21 deletions(-) diff --git a/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs b/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs index 9c8b34822a5..c4bd73bab8a 100644 --- a/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs +++ b/src/HotChocolate/Adapters/src/Adapters.OpenApi.AspNetCore/DynamicOpenApiDocumentTransformer.cs @@ -792,29 +792,29 @@ private static OpenApiSchemaAbstraction ApplyFieldMetadata( string? description, bool isDeprecated) { - // A $ref describes the referenced component, not the field, so it is returned unchanged. -#if NET10_0_OR_GREATER - if (schema is not OpenApiSchema concreteSchema) - { - return schema; - } -#else - if (schema.Reference is not null) + if (description is null && !isDeprecated) { return schema; } - var concreteSchema = schema; +#if NET10_0_OR_GREATER + var target = schema is OpenApiSchema concreteSchema + ? concreteSchema + : CreateAllOfSchema([schema]); +#else + var target = schema.Reference is null + ? schema + : CreateAllOfSchema([schema]); #endif - concreteSchema.Deprecated = isDeprecated; + target.Deprecated = isDeprecated; if (description is not null) { - concreteSchema.Description = description; + target.Description = description; } - return concreteSchema; + return target; } private static OpenApiSchemaAbstraction CreateSchemaReference(string name) diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json index 964b8dcbe37..73f6c67c63b 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0.json @@ -36,6 +36,7 @@ "localDateTime", "localTime", "long", + "nonNullDeprecated", "object", "short", "string", @@ -183,6 +184,21 @@ "description": "The `Long` scalar type represents a signed 64-bit integer.", "format": "int64" }, + "nonNullDeprecated": { + "type": "integer", + "description": "nonNullDeprecated description", + "format": "int32", + "deprecated": true + }, + "nullableObject": { + "allOf": [ + { + "$ref": "#/components/schemas/Object1NullableInput" + } + ], + "description": "nullableObject description", + "deprecated": true + }, "object": { "$ref": "#/components/schemas/Object1NonNullableInput" }, @@ -1074,7 +1090,25 @@ "type": "object", "properties": { "field1A": { - "$ref": "#/components/schemas/Object2NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + ], + "description": "field1A description" + } + } + }, + "Object1NullableInput": { + "type": "object", + "properties": { + "field1A": { + "allOf": [ + { + "$ref": "#/components/schemas/Object2NullableInput" + } + ], + "description": "field1A description" } } }, @@ -1085,7 +1119,25 @@ "type": "object", "properties": { "field1B": { - "$ref": "#/components/schemas/Object3NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + ], + "description": "field1B description" + } + } + }, + "Object2NullableInput": { + "type": "object", + "properties": { + "field1B": { + "allOf": [ + { + "$ref": "#/components/schemas/Object3NullableInput" + } + ], + "description": "field1B description" } } }, @@ -1102,6 +1154,16 @@ } } }, + "Object3NullableInput": { + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, "UserAddress": { "required": [ "street" diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json index 964b8dcbe37..73f6c67c63b 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET10_0_Fusion.json @@ -36,6 +36,7 @@ "localDateTime", "localTime", "long", + "nonNullDeprecated", "object", "short", "string", @@ -183,6 +184,21 @@ "description": "The `Long` scalar type represents a signed 64-bit integer.", "format": "int64" }, + "nonNullDeprecated": { + "type": "integer", + "description": "nonNullDeprecated description", + "format": "int32", + "deprecated": true + }, + "nullableObject": { + "allOf": [ + { + "$ref": "#/components/schemas/Object1NullableInput" + } + ], + "description": "nullableObject description", + "deprecated": true + }, "object": { "$ref": "#/components/schemas/Object1NonNullableInput" }, @@ -1074,7 +1090,25 @@ "type": "object", "properties": { "field1A": { - "$ref": "#/components/schemas/Object2NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + ], + "description": "field1A description" + } + } + }, + "Object1NullableInput": { + "type": "object", + "properties": { + "field1A": { + "allOf": [ + { + "$ref": "#/components/schemas/Object2NullableInput" + } + ], + "description": "field1A description" } } }, @@ -1085,7 +1119,25 @@ "type": "object", "properties": { "field1B": { - "$ref": "#/components/schemas/Object3NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + ], + "description": "field1B description" + } + } + }, + "Object2NullableInput": { + "type": "object", + "properties": { + "field1B": { + "allOf": [ + { + "$ref": "#/components/schemas/Object3NullableInput" + } + ], + "description": "field1B description" } } }, @@ -1102,6 +1154,16 @@ } } }, + "Object3NullableInput": { + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, "UserAddress": { "required": [ "street" diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json index beadf2a3dcf..4c6e44d6636 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0.json @@ -31,6 +31,7 @@ "localDateTime", "localTime", "long", + "nonNullDeprecated", "object", "short", "string", @@ -178,6 +179,21 @@ "description": "The `Long` scalar type represents a signed 64-bit integer.", "format": "int64" }, + "nonNullDeprecated": { + "type": "integer", + "description": "nonNullDeprecated description", + "format": "int32", + "deprecated": true + }, + "nullableObject": { + "allOf": [ + { + "$ref": "#/components/schemas/Object1NullableInput" + } + ], + "description": "nullableObject description", + "deprecated": true + }, "object": { "$ref": "#/components/schemas/Object1NonNullableInput" }, @@ -1017,6 +1033,42 @@ }, "description": "The user's address" }, + "Object3NullableInput": { + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, + "Object2NullableInput": { + "type": "object", + "properties": { + "field1B": { + "allOf": [ + { + "$ref": "#/components/schemas/Object3NullableInput" + } + ], + "description": "field1B description" + } + } + }, + "Object1NullableInput": { + "type": "object", + "properties": { + "field1A": { + "allOf": [ + { + "$ref": "#/components/schemas/Object2NullableInput" + } + ], + "description": "field1A description" + } + } + }, "Object3NonNullableInput": { "required": [ "field1C" @@ -1037,7 +1089,12 @@ "type": "object", "properties": { "field1B": { - "$ref": "#/components/schemas/Object3NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + ], + "description": "field1B description" } } }, @@ -1048,7 +1105,12 @@ "type": "object", "properties": { "field1A": { - "$ref": "#/components/schemas/Object2NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + ], + "description": "field1A description" } } } diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json index beadf2a3dcf..4c6e44d6636 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/OpenApi/__snapshots__/OpenApiIntegrationTestBase.OpenApi_Includes_Initial_Routes_NET9_0_Fusion.json @@ -31,6 +31,7 @@ "localDateTime", "localTime", "long", + "nonNullDeprecated", "object", "short", "string", @@ -178,6 +179,21 @@ "description": "The `Long` scalar type represents a signed 64-bit integer.", "format": "int64" }, + "nonNullDeprecated": { + "type": "integer", + "description": "nonNullDeprecated description", + "format": "int32", + "deprecated": true + }, + "nullableObject": { + "allOf": [ + { + "$ref": "#/components/schemas/Object1NullableInput" + } + ], + "description": "nullableObject description", + "deprecated": true + }, "object": { "$ref": "#/components/schemas/Object1NonNullableInput" }, @@ -1017,6 +1033,42 @@ }, "description": "The user's address" }, + "Object3NullableInput": { + "type": "object", + "properties": { + "field1C": { + "pattern": "^\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?$", + "type": "string", + "description": "field1C description" + } + } + }, + "Object2NullableInput": { + "type": "object", + "properties": { + "field1B": { + "allOf": [ + { + "$ref": "#/components/schemas/Object3NullableInput" + } + ], + "description": "field1B description" + } + } + }, + "Object1NullableInput": { + "type": "object", + "properties": { + "field1A": { + "allOf": [ + { + "$ref": "#/components/schemas/Object2NullableInput" + } + ], + "description": "field1A description" + } + } + }, "Object3NonNullableInput": { "required": [ "field1C" @@ -1037,7 +1089,12 @@ "type": "object", "properties": { "field1B": { - "$ref": "#/components/schemas/Object3NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object3NonNullableInput" + } + ], + "description": "field1B description" } } }, @@ -1048,7 +1105,12 @@ "type": "object", "properties": { "field1A": { - "$ref": "#/components/schemas/Object2NonNullableInput" + "allOf": [ + { + "$ref": "#/components/schemas/Object2NonNullableInput" + } + ], + "description": "field1A description" } } } diff --git a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs index 68173c81760..45039edd828 100644 --- a/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs +++ b/src/HotChocolate/Adapters/test/Adapters.OpenApi.Tests/TestSchema.cs @@ -310,7 +310,13 @@ public sealed record ComplexObjectInput( ushort UnsignedShort, Uri Uri, [property: GraphQLType>] Uri Url, - Guid Uuid); + Guid Uuid, + [property: GraphQLDescription("nullableObject description")] + [property: GraphQLDeprecated("nullableObject deprecated")] + Object1Nullable? NullableObject, + [property: GraphQLDescription("nonNullDeprecated description")] + [property: GraphQLDeprecated("nonNullDeprecated deprecated")] + int NonNullDeprecated = 0); [UnionType(name: "PetUnion")] public interface IPet