From ea26b9899c4ad001568e9cb4e770d953c8394f09 Mon Sep 17 00:00:00 2001 From: Garry Trinder Date: Fri, 13 Dec 2024 07:46:58 +0000 Subject: [PATCH] Add support for generating OpenAPI spec in YAML. Closes #956 (#957) * Add support for generating OpenAPI spec in YAML. Closes #956 * Remove unused namespace reference from OpenApiSpecGeneratorPlugin.cs --------- Co-authored-by: Waldek Mastykarz --- .../RequestLogs/OpenApiSpecGeneratorPlugin.cs | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/dev-proxy-plugins/RequestLogs/OpenApiSpecGeneratorPlugin.cs b/dev-proxy-plugins/RequestLogs/OpenApiSpecGeneratorPlugin.cs index 89c18fc8..5660905b 100644 --- a/dev-proxy-plugins/RequestLogs/OpenApiSpecGeneratorPlugin.cs +++ b/dev-proxy-plugins/RequestLogs/OpenApiSpecGeneratorPlugin.cs @@ -50,11 +50,20 @@ internal enum SpecVersion v3_0 } +[JsonConverter(typeof(JsonStringEnumConverter))] +internal enum SpecFormat +{ + Json, + Yaml +} + internal class OpenApiSpecGeneratorPluginConfiguration { public bool IncludeOptionsRequests { get; set; } = false; public SpecVersion SpecVersion { get; set; } = SpecVersion.v3_0; + + public SpecFormat SpecFormat { get; set; } = SpecFormat.Json; } public class OpenApiSpecGeneratorPlugin(IPluginEvents pluginEvents, IProxyContext context, ILogger logger, ISet urlsToWatch, IConfigurationSection? configSection = null) : BaseReportingPlugin(pluginEvents, context, logger, urlsToWatch, configSection) @@ -364,7 +373,7 @@ request.Context is null || foreach (var openApiDoc in openApiDocs) { var server = openApiDoc.Servers.First(); - var fileName = GetFileNameFromServerUrl(server.Url); + var fileName = GetFileNameFromServerUrl(server.Url, _configuration.SpecFormat); var openApiSpecVersion = _configuration.SpecVersion switch { @@ -373,7 +382,12 @@ request.Context is null || _ => OpenApiSpecVersion.OpenApi3_0 }; - var docString = openApiDoc.SerializeAsJson(openApiSpecVersion); + var docString = _configuration.SpecFormat switch + { + SpecFormat.Json => openApiDoc.SerializeAsJson(openApiSpecVersion), + SpecFormat.Yaml => openApiDoc.SerializeAsYaml(openApiSpecVersion), + _ => openApiDoc.SerializeAsJson(openApiSpecVersion) + }; Logger.LogDebug(" Writing OpenAPI spec to {fileName}...", fileName); File.WriteAllText(fileName, docString); @@ -922,10 +936,16 @@ private void AddOrMergeResponse(OpenApiOperation operation, OpenApiResponses api MergeSchema(contentFromOperation.Schema, apiResponse.Content.First().Value.Schema); } - private static string GetFileNameFromServerUrl(string serverUrl) + private static string GetFileNameFromServerUrl(string serverUrl, SpecFormat format) { var uri = new Uri(serverUrl); - var fileName = $"{uri.Host}-{DateTime.Now:yyyyMMddHHmmss}.json"; + var ext = format switch + { + SpecFormat.Json => "json", + SpecFormat.Yaml => "yaml", + _ => "json" + }; + var fileName = $"{uri.Host}-{DateTime.Now:yyyyMMddHHmmss}.{ext}"; return fileName; }