Skip to content

Commit

Permalink
Merge pull request #1293 from TinaLiu02/parse-server-variable
Browse files Browse the repository at this point in the history
parse server's url with variables when convert openapi spec 3.0 to 2.0
  • Loading branch information
MaggieKimani1 authored Jul 20, 2023
2 parents b91a229 + bd12c69 commit da71361
Show file tree
Hide file tree
Showing 4 changed files with 749 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/Microsoft.OpenApi/Models/OpenApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,18 @@ public void SerializeAsV2(IOpenApiWriter writer)
writer.WriteEndObject();
}

private static string ParseServerUrl(OpenApiServer server)
{
var parsedUrl = server.Url;

var variables = server.Variables;
foreach (var variable in variables.Where(static x => !string.IsNullOrEmpty(x.Value.Default)))
{
parsedUrl = parsedUrl.Replace($"{{{variable.Key}}}", variable.Value.Default);
}
return parsedUrl;
}

private static void WriteHostInfoV2(IOpenApiWriter writer, IList<OpenApiServer> servers)
{
if (servers == null || !servers.Any())
Expand All @@ -299,11 +311,11 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList<OpenApiServer>

// Arbitrarily choose the first server given that V2 only allows
// one host, port, and base path.
var firstServer = servers.First();
var serverUrl = ParseServerUrl(servers.First());

// Divide the URL in the Url property into host and basePath required in OpenAPI V2
// The Url property cannotcontain path templating to be valid for V2 serialization.
var firstServerUrl = new Uri(firstServer.Url, UriKind.RelativeOrAbsolute);
var firstServerUrl = new Uri(serverUrl, UriKind.RelativeOrAbsolute);

// host
if (firstServerUrl.IsAbsoluteUri)
Expand Down Expand Up @@ -337,7 +349,7 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList<OpenApiServer>
var schemes = servers.Select(
s =>
{
Uri.TryCreate(s.Url, UriKind.RelativeOrAbsolute, out var url);
Uri.TryCreate(ParseServerUrl(s), UriKind.RelativeOrAbsolute, out var url);
return url;
})
.Where(
Expand Down
Loading

0 comments on commit da71361

Please sign in to comment.