Skip to content

Commit

Permalink
fix: rename and format JsonSerializerOptions class
Browse files Browse the repository at this point in the history
  • Loading branch information
Amin Purmoradian committed Jul 28, 2024
1 parent 93bea24 commit 61baceb
Show file tree
Hide file tree
Showing 32 changed files with 85 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ public async Task<Response<FileConfiguration>> Get()

var bytes = queryResult.Response.Value;
var json = Encoding.UTF8.GetString(bytes);
var consulConfig = JsonSerializer.Deserialize<FileConfiguration>(json, JsonSerializerOptionsExtensions.Web);
var consulConfig = JsonSerializer.Deserialize<FileConfiguration>(json, JsonSerializerOptionsFactory.Web);

return new OkResponse<FileConfiguration>(consulConfig);
}

public async Task<Response> Set(FileConfiguration ocelotConfiguration)
{
var json = JsonSerializer.Serialize(ocelotConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented);
var json = JsonSerializer.Serialize(ocelotConfiguration, JsonSerializerOptionsFactory.WebWriteIndented);
var bytes = Encoding.UTF8.GetBytes(json);
var kvPair = new KVPair(_configurationKey)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@ public Task<Response<FileConfiguration>> Get()
jsonConfiguration = FileSys.ReadAllText(_environmentFile.FullName);
}

var fileConfiguration = JsonSerializer.Deserialize<FileConfiguration>(jsonConfiguration, JsonSerializerOptionsExtensions.Web);
var fileConfiguration = JsonSerializer.Deserialize<FileConfiguration>(jsonConfiguration, JsonSerializerOptionsFactory.Web);

return Task.FromResult<Response<FileConfiguration>>(new OkResponse<FileConfiguration>(fileConfiguration));
}

public Task<Response> Set(FileConfiguration fileConfiguration)
{
var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented);
var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented);

lock (_lock)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ private async Task Poll()
/// <returns>hash of the config.</returns>
private static string ToJson(FileConfiguration config)
{
var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsExtensions.Web);
var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.Web);
return currentHash;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env
}

var lines = File.ReadAllText(file.FullName);
var config = JsonSerializer.Deserialize<FileConfiguration>(lines, JsonSerializerOptionsExtensions.Web);
var config = JsonSerializer.Deserialize<FileConfiguration>(lines, JsonSerializerOptionsFactory.Web);
if (file.Name.Equals(globalFileInfo.Name, StringComparison.OrdinalIgnoreCase) &&
file.FullName.Equals(globalFileInfo.FullName, StringComparison.OrdinalIgnoreCase))
{
Expand All @@ -145,7 +145,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env
fileConfiguration.Routes.AddRange(config.Routes);
}

return JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented);
return JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented);
}

/// <summary>
Expand All @@ -162,7 +162,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env
public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, FileConfiguration fileConfiguration,
string primaryConfigFile = null, bool? optional = null, bool? reloadOnChange = null) // optional injections
{
var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented);
var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented);
return AddOcelotJsonFile(builder, json, primaryConfigFile, optional, reloadOnChange);
}

Expand Down
29 changes: 0 additions & 29 deletions src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs

This file was deleted.

27 changes: 27 additions & 0 deletions src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;

namespace Ocelot.Infrastructure;

public static class JsonSerializerOptionsFactory
{
public static readonly JsonSerializerOptions Web = new()
{
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
NumberHandling = JsonNumberHandling.AllowReadingFromString,
PropertyNameCaseInsensitive = true,
ReferenceHandler = ReferenceHandler.IgnoreCycles,
WriteIndented = false
};

public static readonly JsonSerializerOptions WebWriteIndented = new()
{
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
NumberHandling = JsonNumberHandling.AllowReadingFromString,
PropertyNameCaseInsensitive = true,
ReferenceHandler = ReferenceHandler.IgnoreCycles,
WriteIndented = true
};
}
2 changes: 1 addition & 1 deletion src/Ocelot/Metadata/DownstreamRouteExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public static T GetMetadata<T>(this DownstreamRoute downstreamRoute, string key,
}

return (T)ConvertTo(typeof(T), metadataValue, downstreamRoute.MetadataOptions,
jsonSerializerOptions ?? JsonSerializerOptionsExtensions.Web);
jsonSerializerOptions ?? JsonSerializerOptionsFactory.Web);
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ public class DistributedCacheRateLimitStorage : IRateLimitStorage
public DistributedCacheRateLimitStorage(IDistributedCache memoryCache) => _memoryCache = memoryCache;

public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime)
=> _memoryCache.SetString(id, JsonSerializer.Serialize(counter, JsonSerializerOptionsExtensions.Web), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime));
=> _memoryCache.SetString(id, JsonSerializer.Serialize(counter, JsonSerializerOptionsFactory.Web), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime));

public bool Exists(string id) => !string.IsNullOrEmpty(_memoryCache.GetString(id));

public RateLimitCounter? Get(string id)
{
var stored = _memoryCache.GetString(id);
return !string.IsNullOrEmpty(stored)
? JsonSerializer.Deserialize<RateLimitCounter>(stored, JsonSerializerOptionsExtensions.Web)
? JsonSerializer.Deserialize<RateLimitCounter>(stored, JsonSerializerOptionsFactory.Web)
: null;
}

Expand Down
4 changes: 2 additions & 2 deletions test/Ocelot.AcceptanceTests/Caching/CachingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ private void ThenTheCounterValueShouldBe(int expected)
LastName = "Test",
};

var testBody1String = JsonSerializer.Serialize(testBody1, JsonSerializerOptionsExtensions.Web);
var testBody1String = JsonSerializer.Serialize(testBody1, JsonSerializerOptionsFactory.Web);

var testBody2 = new TestBody
{
Expand All @@ -309,7 +309,7 @@ private void ThenTheCounterValueShouldBe(int expected)
LastName = "Test",
};

var testBody2String = JsonSerializer.Serialize(testBody2, JsonSerializerOptionsExtensions.Web);
var testBody2String = JsonSerializer.Serialize(testBody2, JsonSerializerOptionsFactory.Web);

return (testBody1String, testBody2String);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string
{
if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration")
{
var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsFactory.Web);

var bytes = Encoding.UTF8.GetBytes(json);

Expand All @@ -110,9 +110,9 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string
// var json = reader.ReadToEnd();
var json = await reader.ReadToEndAsync();

_config = JsonSerializer.Deserialize<FileConfiguration>(json, JsonSerializerOptionsExtensions.Web);
_config = JsonSerializer.Deserialize<FileConfiguration>(json, JsonSerializerOptionsFactory.Web);

var response = JsonSerializer.Serialize(true, JsonSerializerOptionsExtensions.Web);
var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web);

await context.Response.WriteAsync(response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,14 +363,14 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string
{
if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration")
{
var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsFactory.Web);

var bytes = Encoding.UTF8.GetBytes(json);

var base64 = Convert.ToBase64String(bytes);

var kvp = new FakeConsulGetResponse(base64);
json = JsonSerializer.Serialize(new[] { kvp }, JsonSerializerOptionsExtensions.Web);
json = JsonSerializer.Serialize(new[] { kvp }, JsonSerializerOptionsFactory.Web);
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
Expand All @@ -384,9 +384,9 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string
// var json = reader.ReadToEnd();
var json = await reader.ReadToEndAsync();

_config = JsonSerializer.Deserialize<FileConfiguration>(json, JsonSerializerOptionsExtensions.Web);
_config = JsonSerializer.Deserialize<FileConfiguration>(json, JsonSerializerOptionsFactory.Web);

var response = JsonSerializer.Serialize(true, JsonSerializerOptionsExtensions.Web);
var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web);

await context.Response.WriteAsync(response);
}
Expand All @@ -398,7 +398,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string
}
else if (context.Request.Path.Value == $"/v1/health/service/{serviceName}")
{
var json = JsonSerializer.Serialize(_consulServices, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(_consulServices, JsonSerializerOptionsFactory.Web);
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url)
// Use the parsed service name to filter the registered Consul services
var serviceName = pathMatch.Groups["serviceName"].Value;
var services = _consulServices.Where(x => x.Service.Service == serviceName).ToList();
var json = JsonSerializer.Serialize(services, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(services, JsonSerializerOptionsFactory.Web);
json = json.Replace("\"Name\":", "\"Node\":");
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
Expand All @@ -437,7 +437,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url)
if (context.Request.Path.Value == "/v1/catalog/nodes")
{
_counterNodes++;
var json = JsonSerializer.Serialize(_consulNodes, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(_consulNodes, JsonSerializerOptionsFactory.Web);
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string
{
if (context.Request.Path.Value == $"/v1/health/service/{serviceName}")
{
var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsFactory.Web);
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string
},
};

var json = JsonSerializer.Serialize(applications, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(applications, JsonSerializerOptionsFactory.Web);
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ private void GivenThereIsAFakeKubernetesProvider(string serviceName, string name
_receivedToken = values.First();
}

var json = JsonSerializer.Serialize(endpoints, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(endpoints, JsonSerializerOptionsFactory.Web);
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
Expand Down
6 changes: 3 additions & 3 deletions test/Ocelot.AcceptanceTests/Steps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration)
public void GivenThereIsAConfiguration(FileConfiguration from, string toFile)
{
toFile ??= _ocelotConfigFileName;
var jsonConfiguration = JsonSerializer.Serialize(from, JsonSerializerOptionsExtensions.WebWriteIndented);
var jsonConfiguration = JsonSerializer.Serialize(from, JsonSerializerOptionsFactory.WebWriteIndented);
File.WriteAllText(toFile, jsonConfiguration);
Files.Add(toFile); // register for disposing
}
Expand Down Expand Up @@ -753,7 +753,7 @@ internal async Task<BearerToken> GivenIHaveATokenWithForm(string url, IEnumerabl
var response = await httpClient.PostAsync(tokenUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
_token = JsonSerializer.Deserialize<BearerToken>(responseContent, JsonSerializerOptionsExtensions.Web);
_token = JsonSerializer.Deserialize<BearerToken>(responseContent, JsonSerializerOptionsFactory.Web);
return _token;
}

Expand Down Expand Up @@ -955,7 +955,7 @@ public void GivenThePostHasContentType(string postContent)

public void GivenThePostHasGzipContent(object input)
{
var json = JsonSerializer.Serialize(input, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(input, JsonSerializerOptionsFactory.Web);
var jsonBytes = Encoding.UTF8.GetBytes(json);
var ms = new MemoryStream();
using (var gzip = new GZipStream(ms, CompressionMode.Compress, true))
Expand Down
2 changes: 1 addition & 1 deletion test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url)
{
if (context.Request.Path.Value == "/v1/health/service/product")
{
var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsExtensions.Web);
var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsFactory.Web);
context.Response.Headers.Append("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
Expand Down
2 changes: 1 addition & 1 deletion test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio
{
var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json");

var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web);
var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web);

if (File.Exists(configurationPath))
{
Expand Down
2 changes: 1 addition & 1 deletion test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio
{
var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json");

var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web);
var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web);

if (File.Exists(configurationPath))
{
Expand Down
2 changes: 1 addition & 1 deletion test/Ocelot.Benchmarks/PayloadBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ private void GivenOcelotIsRunning(string url)
public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration)
{
var configurationPath = Path.Combine(AppContext.BaseDirectory, ConfigurationBuilderExtensions.PrimaryConfigFile);
var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web);
var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web);

if (File.Exists(configurationPath))
{
Expand Down
Loading

0 comments on commit 61baceb

Please sign in to comment.