|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using Microsoft.OpenApi.Models; |
| 4 | +using Microsoft.OpenApi.Properties; |
| 5 | + |
| 6 | +namespace Microsoft.OpenApi.Extensions; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Extension methods for <see cref="OpenApiServer"/> serialization. |
| 10 | +/// </summary> |
| 11 | +public static class OpenApiServerExtensions |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Replaces URL variables in a server's URL |
| 15 | + /// </summary> |
| 16 | + /// <param name="server">The OpenAPI server object</param> |
| 17 | + /// <param name="values">The server variable values that will be used to replace the default values.</param> |
| 18 | + /// <returns>A URL with the provided variables substituted.</returns> |
| 19 | + /// <exception cref="ArgumentException"> |
| 20 | + /// Thrown when: |
| 21 | + /// 1. A substitution has no valid value in both the supplied dictionary and the default |
| 22 | + /// 2. A substitution's value is not available in the enum provided |
| 23 | + /// </exception> |
| 24 | + public static string ReplaceServerUrlVariables(this OpenApiServer server, IDictionary<string, string> values = null) |
| 25 | + { |
| 26 | + var parsedUrl = server.Url; |
| 27 | + foreach (var variable in server.Variables) |
| 28 | + { |
| 29 | + // Try to get the value from the provided values |
| 30 | + if (values is not { } v || !v.TryGetValue(variable.Key, out var value) || string.IsNullOrEmpty(value)) |
| 31 | + { |
| 32 | + // Fall back to the default value |
| 33 | + value = variable.Value.Default; |
| 34 | + } |
| 35 | + |
| 36 | + // Validate value |
| 37 | + if (string.IsNullOrEmpty(value)) |
| 38 | + { |
| 39 | + // According to the spec, the variable's default value is required. |
| 40 | + // This code path should be hit when a value isn't provided & a default value isn't available |
| 41 | + throw new ArgumentException( |
| 42 | + string.Format(SRResource.ParseServerUrlDefaultValueNotAvailable, variable.Key), nameof(server)); |
| 43 | + } |
| 44 | + |
| 45 | + // If an enum is provided, the array should not be empty & the value should exist in the enum |
| 46 | + if (variable.Value.Enum is {} e && (e.Count == 0 || !e.Contains(value))) |
| 47 | + { |
| 48 | + throw new ArgumentException( |
| 49 | + string.Format(SRResource.ParseServerUrlValueNotValid, value, variable.Key), nameof(values)); |
| 50 | + } |
| 51 | + |
| 52 | + parsedUrl = parsedUrl.Replace($"{{{variable.Key}}}", value); |
| 53 | + } |
| 54 | + |
| 55 | + return parsedUrl; |
| 56 | + } |
| 57 | +} |
0 commit comments