Skip to content

Commit c2ae2dd

Browse files
committed
Add method for CSDL to OpenAPI conversion
1 parent e0f0ed6 commit c2ae2dd

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/Microsoft.OpenApi.Hidi/OpenApiService.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,49 @@ public static void ProcessOpenApiDocument(
106106
textWriter.Flush();
107107
}
108108

109+
/// <summary>
110+
/// Converts CSDL to OpenAPI
111+
/// </summary>
112+
/// <param name="csdl">The CSDL stream.</param>
113+
/// <returns>An OpenAPI document.</returns>
114+
public static OpenApiDocument ConvertCsdlToOpenApi(Stream csdl)
115+
{
116+
using var reader = new StreamReader(csdl);
117+
var csdlText = reader.ReadToEndAsync().GetAwaiter().GetResult();
118+
var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader());
119+
120+
var settings = new OpenApiConvertSettings()
121+
{
122+
EnableKeyAsSegment = true,
123+
EnableOperationId = true,
124+
PrefixEntityTypeNameBeforeKey = true,
125+
TagDepth = 2,
126+
EnablePagination = true,
127+
EnableDiscriminatorValue = false,
128+
EnableDerivedTypesReferencesForRequestBody = false,
129+
EnableDerivedTypesReferencesForResponses = false,
130+
ShowRootPath = true,
131+
ShowLinks = true
132+
};
133+
OpenApiDocument document = edmModel.ConvertToOpenApi(settings);
134+
135+
document = FixReferences(document);
136+
137+
return document;
138+
}
139+
140+
public static OpenApiDocument FixReferences(OpenApiDocument document)
141+
{
142+
// This method is only needed because the output of ConvertToOpenApi isn't quite a valid OpenApiDocument instance.
143+
// So we write it out, and read it back in again to fix it up.
144+
145+
var sb = new StringBuilder();
146+
document.SerializeAsV3(new OpenApiYamlWriter(new StringWriter(sb)));
147+
var doc = new OpenApiStringReader().Read(sb.ToString(), out _);
148+
149+
return doc;
150+
}
151+
109152
private static Stream GetStream(string input)
110153
{
111154
Stream stream;

0 commit comments

Comments
 (0)