Skip to content

Commit 9f51814

Browse files
committed
Refactor OpenAPI spec version handling to use enum type and improve version validation
1 parent d1ac06c commit 9f51814

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

dev-proxy-plugins/RequestLogs/OpenApiSpecGeneratorPlugin.cs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
using System.Collections.Specialized;
1616
using Microsoft.Extensions.Logging;
1717
using Microsoft.DevProxy.Abstractions.LanguageModel;
18+
using System.Text.Json.Serialization;
1819

1920
namespace Microsoft.DevProxy.Plugins.RequestLogs;
2021

@@ -42,11 +43,18 @@ public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion)
4243
}
4344
}
4445

46+
[JsonConverter(typeof(JsonStringEnumConverter))]
47+
internal enum SpecVersion
48+
{
49+
v2_0,
50+
v3_0
51+
}
52+
4553
internal class OpenApiSpecGeneratorPluginConfiguration
4654
{
4755
public bool IncludeOptionsRequests { get; set; } = false;
4856

49-
public string SpecVersion { get; set; } = "3";
57+
public SpecVersion SpecVersion { get; set; } = SpecVersion.v3_0;
5058
}
5159

5260
public class OpenApiSpecGeneratorPlugin(IPluginEvents pluginEvents, IProxyContext context, ILogger logger, ISet<UrlToWatch> urlsToWatch, IConfigurationSection? configSection = null) : BaseReportingPlugin(pluginEvents, context, logger, urlsToWatch, configSection)
@@ -294,12 +302,6 @@ public override async Task RegisterAsync()
294302

295303
ConfigSection?.Bind(_configuration);
296304

297-
if (_configuration.SpecVersion != "2" && _configuration.SpecVersion != "3")
298-
{
299-
Logger.LogError("OpenAPI spec version is not supported. Supported versions are 2 and 3.");
300-
return;
301-
}
302-
303305
PluginEvents.AfterRecordingStop += AfterRecordingStopAsync;
304306
}
305307

@@ -364,7 +366,12 @@ request.Context is null ||
364366
var server = openApiDoc.Servers.First();
365367
var fileName = GetFileNameFromServerUrl(server.Url);
366368

367-
var openApiSpecVersion = _configuration.SpecVersion == "2" ? OpenApiSpecVersion.OpenApi2_0 : OpenApiSpecVersion.OpenApi3_0;
369+
var openApiSpecVersion = _configuration.SpecVersion switch
370+
{
371+
SpecVersion.v2_0 => OpenApiSpecVersion.OpenApi2_0,
372+
SpecVersion.v3_0 => OpenApiSpecVersion.OpenApi3_0,
373+
_ => OpenApiSpecVersion.OpenApi3_0
374+
};
368375

369376
var docString = openApiDoc.SerializeAsJson(openApiSpecVersion);
370377

0 commit comments

Comments
 (0)