Skip to content

Commit

Permalink
Add support for generating OpenAPI spec in YAML. Closes #956 (#957)
Browse files Browse the repository at this point in the history
* Add support for generating OpenAPI spec in YAML. Closes #956

* Remove unused namespace reference from OpenApiSpecGeneratorPlugin.cs

---------

Co-authored-by: Waldek Mastykarz <[email protected]>
  • Loading branch information
garrytrinder and waldekmastykarz authored Dec 13, 2024
1 parent a8d59ee commit ea26b98
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions dev-proxy-plugins/RequestLogs/OpenApiSpecGeneratorPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<UrlToWatch> urlsToWatch, IConfigurationSection? configSection = null) : BaseReportingPlugin(pluginEvents, context, logger, urlsToWatch, configSection)
Expand Down Expand Up @@ -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
{
Expand All @@ -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);
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit ea26b98

Please sign in to comment.