| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | using System.Text.Json.Serialization.Metadata; |
| | | 4 | | using Elsa.Extensions; |
| | | 5 | | using Elsa.Resilience.Options; |
| | | 6 | | using Microsoft.Extensions.Options; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Resilience.Serialization; |
| | | 9 | | |
| | | 10 | | public class ResilienceStrategySerializer |
| | | 11 | | { |
| | | 12 | | private readonly JsonSerializerOptions _serializerOptions; |
| | | 13 | | |
| | 1 | 14 | | public ResilienceStrategySerializer(IOptions<ResilienceOptions> options) |
| | | 15 | | { |
| | 1 | 16 | | var serializerOptions = new JsonSerializerOptions |
| | 1 | 17 | | { |
| | 1 | 18 | | TypeInfoResolver = new DefaultJsonTypeInfoResolver().WithAddedModifier(typeInfo => |
| | 1 | 19 | | { |
| | 0 | 20 | | if (typeInfo.Type != typeof(IResilienceStrategy)) |
| | 0 | 21 | | return; |
| | 1 | 22 | | |
| | 0 | 23 | | if (typeInfo.Kind != JsonTypeInfoKind.Object) |
| | 0 | 24 | | return; |
| | 1 | 25 | | |
| | 0 | 26 | | var polymorphismOptions = new JsonPolymorphismOptions |
| | 0 | 27 | | { |
| | 0 | 28 | | TypeDiscriminatorPropertyName = "$type" |
| | 0 | 29 | | }; |
| | 1 | 30 | | |
| | 0 | 31 | | foreach (var type in options.Value.StrategyTypes.ToList()) |
| | 0 | 32 | | polymorphismOptions.DerivedTypes.Add(new(type, type.Name)); |
| | 1 | 33 | | |
| | 0 | 34 | | typeInfo.PolymorphismOptions = polymorphismOptions; |
| | 0 | 35 | | }), |
| | 1 | 36 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 1 | 37 | | PropertyNameCaseInsensitive = true, |
| | 1 | 38 | | NumberHandling = JsonNumberHandling.AllowReadingFromString |
| | 1 | 39 | | }.WithConverters(new JsonStringEnumConverter()); |
| | | 40 | | |
| | 1 | 41 | | _serializerOptions = serializerOptions; |
| | 1 | 42 | | } |
| | | 43 | | |
| | 0 | 44 | | public JsonSerializerOptions SerializerOptions => _serializerOptions; |
| | 0 | 45 | | public string Serialize(IResilienceStrategy strategy) => JsonSerializer.Serialize(strategy, _serializerOptions); |
| | 0 | 46 | | public string SerializeMany(IEnumerable<IResilienceStrategy> strategies) => JsonSerializer.Serialize(strategies, _se |
| | 0 | 47 | | public IResilienceStrategy Deserialize(string json) => JsonSerializer.Deserialize<IResilienceStrategy>(json, _serial |
| | 0 | 48 | | public IEnumerable<IResilienceStrategy> DeserializeMany(string json) => JsonSerializer.Deserialize<IEnumerable<IResi |
| | | 49 | | } |