From 0ecaed80638ebf6de212e0324895873191b6ee3e Mon Sep 17 00:00:00 2001 From: Darrel Miller Date: Sun, 3 Apr 2022 20:40:05 -0400 Subject: [PATCH] Convert anyOf/oneOf to allOf with first schema when writing v2 --- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index 74aed7da1..036222261 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System.Collections.Generic; +using System.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -260,7 +261,7 @@ public void SerializeAsV3(IOpenApiWriter writer) { Reference.SerializeAsV3(writer); return; - } + } else { if (Reference.IsExternal) // Temporary until v2 @@ -644,6 +645,20 @@ internal void WriteAsSchemaProperties( // allOf writer.WriteOptionalCollection(OpenApiConstants.AllOf, AllOf, (w, s) => s.SerializeAsV2(w)); + // If there isn't already an AllOf, and the schema contains a oneOf or anyOf write an allOf with the first + // schema in the list as an attempt to guess at a graceful downgrade situation. + if (AllOf == null || AllOf.Count == 0) + { + // anyOf (Not Supported in V2) - Write the first schema only as an allOf. + writer.WriteOptionalCollection(OpenApiConstants.AllOf, AnyOf.Take(1), (w, s) => s.SerializeAsV2(w)); + + if (AnyOf == null || AnyOf.Count == 0) + { + // oneOf (Not Supported in V2) - Write the first schema only as an allOf. + writer.WriteOptionalCollection(OpenApiConstants.AllOf, OneOf.Take(1), (w, s) => s.SerializeAsV2(w)); + } + } + // properties writer.WriteOptionalMap(OpenApiConstants.Properties, Properties, (w, key, s) => s.SerializeAsV2(w, Required, key));