Skip to content

Commit

Permalink
parse server's url with variables when convert openapi 3.0 to 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
TinaLiu02 committed Jul 18, 2023
1 parent b91a229 commit da0fd1c
Show file tree
Hide file tree
Showing 4 changed files with 752 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/Microsoft.OpenApi/Models/OpenApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,21 @@ 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)
{
if (!string.IsNullOrEmpty(variable.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 +314,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 +352,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 da0fd1c

Please sign in to comment.