|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Linq.Expressions; |
| 5 | +using System.Reflection; |
| 6 | +using JetBrains.Annotations; |
| 7 | +using JsonApiDotNetCore.OpenApi; |
| 8 | +using Newtonsoft.Json; |
| 9 | +using Newtonsoft.Json.Serialization; |
| 10 | + |
| 11 | +namespace JsonApiDotNetCore.OpenApiClient |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Base class to inherit auto-generated client from. Enables to mark fields to be explicitly included in a request body, even if they are null or |
| 15 | + /// default. |
| 16 | + /// </summary> |
| 17 | + [PublicAPI] |
| 18 | + public abstract class JsonApiClient : IJsonApiClient |
| 19 | + { |
| 20 | + private readonly JsonApiJsonConverter _jsonApiJsonConverter = new(); |
| 21 | + |
| 22 | + protected void SetSerializerSettingsForJsonApi(JsonSerializerSettings settings) |
| 23 | + { |
| 24 | + ArgumentGuard.NotNull(settings, nameof(settings)); |
| 25 | + |
| 26 | + settings.Converters.Add(_jsonApiJsonConverter); |
| 27 | + } |
| 28 | + |
| 29 | + /// <inheritdoc /> |
| 30 | + public IDisposable RegisterAttributesForRequestDocument<TRequestDocument, TAttributesObject>(TRequestDocument requestDocument, |
| 31 | + params Expression<Func<TAttributesObject, object>>[] alwaysIncludedAttributeSelectors) |
| 32 | + where TRequestDocument : class |
| 33 | + { |
| 34 | + ArgumentGuard.NotNull(requestDocument, nameof(requestDocument)); |
| 35 | + |
| 36 | + var attributeNames = new HashSet<string>(); |
| 37 | + |
| 38 | + foreach (Expression<Func<TAttributesObject, object>> selector in alwaysIncludedAttributeSelectors) |
| 39 | + { |
| 40 | + if (RemoveConvert(selector.Body) is MemberExpression selectorBody) |
| 41 | + { |
| 42 | + attributeNames.Add(selectorBody.Member.Name); |
| 43 | + } |
| 44 | + else |
| 45 | + { |
| 46 | + throw new ArgumentException($"The expression '{selector}' should select a single property. For example: 'article => article.Title'."); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + _jsonApiJsonConverter.RegisterRequestDocument(requestDocument, new AttributeNamesContainer(attributeNames, typeof(TAttributesObject))); |
| 51 | + |
| 52 | + return new AttributesRegistrationScope(_jsonApiJsonConverter, requestDocument); |
| 53 | + } |
| 54 | + |
| 55 | + private static Expression RemoveConvert(Expression expression) |
| 56 | + { |
| 57 | + Expression innerExpression = expression; |
| 58 | + |
| 59 | + while (true) |
| 60 | + { |
| 61 | + if (innerExpression is UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression) |
| 62 | + { |
| 63 | + innerExpression = unaryExpression.Operand; |
| 64 | + } |
| 65 | + else |
| 66 | + { |
| 67 | + return innerExpression; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private sealed class JsonApiJsonConverter : JsonConverter |
| 73 | + { |
| 74 | + private readonly Dictionary<object, AttributeNamesContainer> _alwaysIncludedAttributesPerRequestDocumentInstance = new(); |
| 75 | + private readonly Dictionary<Type, ISet<object>> _requestDocumentInstancesPerRequestDocumentType = new(); |
| 76 | + private bool _isSerializing; |
| 77 | + |
| 78 | + public override bool CanRead => false; |
| 79 | + |
| 80 | + public void RegisterRequestDocument(object requestDocument, AttributeNamesContainer attributes) |
| 81 | + { |
| 82 | + _alwaysIncludedAttributesPerRequestDocumentInstance[requestDocument] = attributes; |
| 83 | + |
| 84 | + Type requestDocumentType = requestDocument.GetType(); |
| 85 | + |
| 86 | + if (!_requestDocumentInstancesPerRequestDocumentType.ContainsKey(requestDocumentType)) |
| 87 | + { |
| 88 | + _requestDocumentInstancesPerRequestDocumentType[requestDocumentType] = new HashSet<object>(); |
| 89 | + } |
| 90 | + |
| 91 | + _requestDocumentInstancesPerRequestDocumentType[requestDocumentType].Add(requestDocument); |
| 92 | + } |
| 93 | + |
| 94 | + public void RemoveAttributeRegistration(object requestDocument) |
| 95 | + { |
| 96 | + if (_alwaysIncludedAttributesPerRequestDocumentInstance.ContainsKey(requestDocument)) |
| 97 | + { |
| 98 | + _alwaysIncludedAttributesPerRequestDocumentInstance.Remove(requestDocument); |
| 99 | + |
| 100 | + Type requestDocumentType = requestDocument.GetType(); |
| 101 | + _requestDocumentInstancesPerRequestDocumentType[requestDocumentType].Remove(requestDocument); |
| 102 | + |
| 103 | + if (!_requestDocumentInstancesPerRequestDocumentType[requestDocumentType].Any()) |
| 104 | + { |
| 105 | + _requestDocumentInstancesPerRequestDocumentType.Remove(requestDocumentType); |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + public override bool CanConvert(Type objectType) |
| 111 | + { |
| 112 | + ArgumentGuard.NotNull(objectType, nameof(objectType)); |
| 113 | + |
| 114 | + return !_isSerializing && _requestDocumentInstancesPerRequestDocumentType.ContainsKey(objectType); |
| 115 | + } |
| 116 | + |
| 117 | + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) |
| 118 | + { |
| 119 | + throw new UnreachableCodeException(); |
| 120 | + } |
| 121 | + |
| 122 | + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) |
| 123 | + { |
| 124 | + ArgumentGuard.NotNull(writer, nameof(writer)); |
| 125 | + ArgumentGuard.NotNull(value, nameof(value)); |
| 126 | + ArgumentGuard.NotNull(serializer, nameof(serializer)); |
| 127 | + |
| 128 | + if (_alwaysIncludedAttributesPerRequestDocumentInstance.ContainsKey(value)) |
| 129 | + { |
| 130 | + AttributeNamesContainer attributeNamesContainer = _alwaysIncludedAttributesPerRequestDocumentInstance[value]; |
| 131 | + serializer.ContractResolver = new JsonApiDocumentContractResolver(attributeNamesContainer); |
| 132 | + } |
| 133 | + |
| 134 | + try |
| 135 | + { |
| 136 | + _isSerializing = true; |
| 137 | + serializer.Serialize(writer, value); |
| 138 | + } |
| 139 | + finally |
| 140 | + { |
| 141 | + _isSerializing = false; |
| 142 | + } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + private sealed class AttributeNamesContainer |
| 147 | + { |
| 148 | + private readonly ISet<string> _attributeNames; |
| 149 | + private readonly Type _containerType; |
| 150 | + |
| 151 | + public AttributeNamesContainer(ISet<string> attributeNames, Type containerType) |
| 152 | + { |
| 153 | + ArgumentGuard.NotNull(attributeNames, nameof(attributeNames)); |
| 154 | + ArgumentGuard.NotNull(containerType, nameof(containerType)); |
| 155 | + |
| 156 | + _attributeNames = attributeNames; |
| 157 | + _containerType = containerType; |
| 158 | + } |
| 159 | + |
| 160 | + public bool ContainsAttribute(string name) |
| 161 | + { |
| 162 | + return _attributeNames.Contains(name); |
| 163 | + } |
| 164 | + |
| 165 | + public bool ContainerMatchesType(Type type) |
| 166 | + { |
| 167 | + return _containerType == type; |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + private sealed class AttributesRegistrationScope : IDisposable |
| 172 | + { |
| 173 | + private readonly JsonApiJsonConverter _jsonApiJsonConverter; |
| 174 | + private readonly object _requestDocument; |
| 175 | + |
| 176 | + public AttributesRegistrationScope(JsonApiJsonConverter jsonApiJsonConverter, object requestDocument) |
| 177 | + { |
| 178 | + ArgumentGuard.NotNull(jsonApiJsonConverter, nameof(jsonApiJsonConverter)); |
| 179 | + ArgumentGuard.NotNull(requestDocument, nameof(requestDocument)); |
| 180 | + |
| 181 | + _jsonApiJsonConverter = jsonApiJsonConverter; |
| 182 | + _requestDocument = requestDocument; |
| 183 | + } |
| 184 | + |
| 185 | + public void Dispose() |
| 186 | + { |
| 187 | + _jsonApiJsonConverter.RemoveAttributeRegistration(_requestDocument); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + private sealed class JsonApiDocumentContractResolver : DefaultContractResolver |
| 192 | + { |
| 193 | + private readonly AttributeNamesContainer _attributeNamesContainer; |
| 194 | + |
| 195 | + public JsonApiDocumentContractResolver(AttributeNamesContainer attributeNamesContainer) |
| 196 | + { |
| 197 | + ArgumentGuard.NotNull(attributeNamesContainer, nameof(attributeNamesContainer)); |
| 198 | + |
| 199 | + _attributeNamesContainer = attributeNamesContainer; |
| 200 | + } |
| 201 | + |
| 202 | + protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) |
| 203 | + { |
| 204 | + JsonProperty property = base.CreateProperty(member, memberSerialization); |
| 205 | + |
| 206 | + if (_attributeNamesContainer.ContainerMatchesType(property.DeclaringType)) |
| 207 | + { |
| 208 | + if (_attributeNamesContainer.ContainsAttribute(property.UnderlyingName)) |
| 209 | + { |
| 210 | + property.NullValueHandling = NullValueHandling.Include; |
| 211 | + property.DefaultValueHandling = DefaultValueHandling.Include; |
| 212 | + } |
| 213 | + else |
| 214 | + { |
| 215 | + property.NullValueHandling = NullValueHandling.Ignore; |
| 216 | + property.DefaultValueHandling = DefaultValueHandling.Ignore; |
| 217 | + } |
| 218 | + } |
| 219 | + |
| 220 | + return property; |
| 221 | + } |
| 222 | + } |
| 223 | + } |
| 224 | +} |
0 commit comments