|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Text.Json; |
| 8 | +using System.Text.Json.Serialization; |
| 9 | +using Elastic.Clients.Elasticsearch.Core; |
| 10 | + |
| 11 | +namespace Elastic.Clients.Elasticsearch.Serialization; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// A base converter for any multi-item (>2 items) unions. The code-generator creates a |
| 15 | +/// derived type which populates the fields in its constructor. |
| 16 | +/// IMPORTANT: This is a MVP implementation which meets the requirements for the currently |
| 17 | +/// generated multi-item unions. Additional logic may be needed when we first encounter |
| 18 | +/// other item types. In the interests of time, we are not covering all cases for now. |
| 19 | +/// </summary> |
| 20 | +internal abstract class MultiItemUnionConverter<TUnion, TEnum> : JsonConverter<TUnion> |
| 21 | + where TUnion : IComplexUnion<TEnum> |
| 22 | + where TEnum : Enum |
| 23 | +{ |
| 24 | + // Used when serializing to specify the type for each enum kind. |
| 25 | + protected Dictionary<TEnum, Type> _types; |
| 26 | + |
| 27 | + // Used when creating an instance of the TUnion for a specific type. |
| 28 | + protected Dictionary<Type, Func<object, TUnion>> _factories; |
| 29 | + |
| 30 | + // Used when deserializing objects, to determine which type we have. |
| 31 | + protected Dictionary<string, Type> _uniquePropertyToType; |
| 32 | + |
| 33 | + protected Type _arrayType; // For now, we handle only unions with one item being defined as an array |
| 34 | + |
| 35 | + public override TUnion? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 36 | + { |
| 37 | + const string exceptionMessage = "Unable to match JSON object to union item."; |
| 38 | + |
| 39 | + // Plan of attack!! |
| 40 | + // - If the token is start object: |
| 41 | + // - For types which are objects, we need to identify required properties |
| 42 | + // - Determine if each object has a unique required property (if not we need to find unique combinations) |
| 43 | + // - If none are unique, we may struggle, but we can also check for unique optional properties |
| 44 | + // - If the token is a literal value, see if we have a matching literal available |
| 45 | + // - If the token is the start of an array, do we have an array type identified (we currently only support one array-based item). |
| 46 | + |
| 47 | + if (_factories is null) |
| 48 | + ThrowHelper.ThrowJsonException("No factories have been registered for deserialization."); |
| 49 | + |
| 50 | + // We'll be handling an object |
| 51 | + if (reader.TokenType == JsonTokenType.StartObject) |
| 52 | + { |
| 53 | + var readerCopy = reader; // We need a copy to use when reading ahead |
| 54 | + |
| 55 | + if (_uniquePropertyToType is null) |
| 56 | + ThrowHelper.ThrowJsonException(exceptionMessage); |
| 57 | + |
| 58 | + using var jsonDoc = JsonDocument.ParseValue(ref readerCopy); |
| 59 | + |
| 60 | + if (jsonDoc is null) |
| 61 | + ThrowHelper.ThrowJsonException(exceptionMessage); |
| 62 | + |
| 63 | + Type? matchedType = null; |
| 64 | + |
| 65 | + // Loop through the unique properties of each possible object. |
| 66 | + // Once we find a match we can stop checking any further. |
| 67 | + foreach (var item in _uniquePropertyToType) |
| 68 | + { |
| 69 | + if (jsonDoc.RootElement.TryGetProperty(item.Key, out _)) |
| 70 | + { |
| 71 | + // We've matched a unique property in the JSON object, so now know the type |
| 72 | + matchedType = item.Value; |
| 73 | + break; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + if (matchedType is null) |
| 78 | + ThrowHelper.ThrowJsonException(exceptionMessage); |
| 79 | + |
| 80 | + if (!_factories.TryGetValue(matchedType, out var factory)) |
| 81 | + ThrowHelper.ThrowJsonException("Unable to locate factory for multi-item union object item."); |
| 82 | + |
| 83 | + // Since we now know the type and have the factory for that type, we can deserialize the object |
| 84 | + // and pass it to the factory to create the instance. |
| 85 | + |
| 86 | + var value = JsonSerializer.Deserialize(ref reader, matchedType, options); |
| 87 | + |
| 88 | + return factory.Invoke(value); |
| 89 | + } |
| 90 | + |
| 91 | + if (reader.TokenType == JsonTokenType.String) |
| 92 | + { |
| 93 | + var value = reader.GetString(); |
| 94 | + reader.Read(); |
| 95 | + |
| 96 | + if (!_factories.TryGetValue(typeof(string), out var factory)) |
| 97 | + ThrowHelper.ThrowJsonException("Unable to locate factory for multi-item union accepting a string value."); |
| 98 | + |
| 99 | + return factory.Invoke(value); |
| 100 | + } |
| 101 | + |
| 102 | + if (reader.TokenType == JsonTokenType.StartArray) |
| 103 | + { |
| 104 | + if (_arrayType is null) |
| 105 | + ThrowHelper.ThrowJsonException(exceptionMessage); |
| 106 | + |
| 107 | + if (!_factories.TryGetValue(_arrayType, out var factory)) |
| 108 | + ThrowHelper.ThrowJsonException("Unable to locate factory for multi-item union accepting an array value."); |
| 109 | + |
| 110 | + var value = JsonSerializer.Deserialize(ref reader, _arrayType, options); |
| 111 | + |
| 112 | + return factory.Invoke(value); |
| 113 | + } |
| 114 | + |
| 115 | + ThrowHelper.ThrowJsonException($"Unable to deserialize JSON representing {typeof(TUnion)}."); |
| 116 | + |
| 117 | + return default; // We never reach here! |
| 118 | + } |
| 119 | + |
| 120 | + public override void Write(Utf8JsonWriter writer, TUnion value, JsonSerializerOptions options) |
| 121 | + { |
| 122 | + if (_types is null) |
| 123 | + ThrowHelper.ThrowJsonException("No types have been registered for serialization."); |
| 124 | + |
| 125 | + if (value is null) |
| 126 | + { |
| 127 | + writer.WriteNullValue(); |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + var serializeAsType = _types[value.ValueKind]; |
| 132 | + |
| 133 | + JsonSerializer.Serialize(writer, value.Value, serializeAsType, options); |
| 134 | + } |
| 135 | +} |
0 commit comments