From 7757bec34211e6cda9e722d0157366988a796f64 Mon Sep 17 00:00:00 2001 From: Maxim Markelow Date: Wed, 30 Oct 2024 00:02:34 +0300 Subject: [PATCH] Added some comments --- Directory.Build.props | 4 +- .../Entities/Issue.cs | 6 +-- ...numWithEnumMemberAttributeJsonConverter.cs | 40 +++++++++++++++++++ .../QueueLocalFieldTypeConverter.cs | 32 --------------- ...rter.cs => YandexDateTimeJsonConverter.cs} | 5 ++- ...=> YandexNullableDateTimeJsonConverter.cs} | 5 ++- Mindbox.YandexTracker/YandexTrackerClient.cs | 6 +-- 7 files changed, 56 insertions(+), 42 deletions(-) create mode 100644 Mindbox.YandexTracker/JsonConverters/EnumWithEnumMemberAttributeJsonConverter.cs delete mode 100644 Mindbox.YandexTracker/JsonConverters/QueueLocalFieldTypeConverter.cs rename Mindbox.YandexTracker/JsonConverters/{YandexDateTimeConverter.cs => YandexDateTimeJsonConverter.cs} (78%) rename Mindbox.YandexTracker/JsonConverters/{YandexNullableDateTimeConverter.cs => YandexNullableDateTimeJsonConverter.cs} (78%) diff --git a/Directory.Build.props b/Directory.Build.props index 5f9d263..7ff1acd 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -13,8 +13,8 @@ true - 1 - 1 + 2 + 0 $(BuildNumber) 0 $(VersionMajor).$(VersionMinor).$(BuildNumber)$(VersionTag) diff --git a/Mindbox.YandexTracker.Abstractions/Entities/Issue.cs b/Mindbox.YandexTracker.Abstractions/Entities/Issue.cs index 997cf7a..e581528 100644 --- a/Mindbox.YandexTracker.Abstractions/Entities/Issue.cs +++ b/Mindbox.YandexTracker.Abstractions/Entities/Issue.cs @@ -143,9 +143,9 @@ public sealed record Issue /// Кастомные поля задачи /// /// - /// Необходимость JsonNode заключается в том, что мы не знаем какое объект придет к нам с сервера под заданным ключем. - /// Чтобы не поломать работу было принято использовать JToken и ограничить доступ к словарю через GetCustomField и - /// SetCustomField + /// Используем JsonElement, потому что на этапе компиляции мы не знаем, какой объект придет к нам с сервера под + /// заданным ключиком. Чтобы не поломать работу было принято использовать JsonElement и ограничить доступ к словарю через + /// GetCustomField и SetCustomField. /// internal Dictionary CustomFields { get; init; } = []; diff --git a/Mindbox.YandexTracker/JsonConverters/EnumWithEnumMemberAttributeJsonConverter.cs b/Mindbox.YandexTracker/JsonConverters/EnumWithEnumMemberAttributeJsonConverter.cs new file mode 100644 index 0000000..d78e50f --- /dev/null +++ b/Mindbox.YandexTracker/JsonConverters/EnumWithEnumMemberAttributeJsonConverter.cs @@ -0,0 +1,40 @@ +using System; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Mindbox.YandexTracker.JsonConverters; + +/// +/// Кастомный конвертер для сериализации/десериализации enum'ов с атрибутом EnumMemberAttribute. +/// +/// +/// При конвертации в json значение берется из атрибута. +/// +internal class EnumWithEnumMemberAttributeJsonConverter : JsonConverter where T: Enum +{ + public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? enumString = reader.GetString(); + for (var i = 0; i < typeToConvert.GetFields().Length; i++) + { + var field = typeToConvert.GetFields()[i]; + + if (field.GetCustomAttribute()?.Value == enumString) + { + return (T)field.GetValue(null)!; + } + } + + if (enumString == null) throw new JsonException($"Unknown value for {nameof(QueueLocalFieldType)} ({enumString})"); + + return (T)Enum.Parse(typeToConvert, enumString, true); + } + + public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) + { + var enumMemberAttribute = value.GetType().GetField(value.ToString())?.GetCustomAttribute(); + writer.WriteStringValue(enumMemberAttribute != null ? enumMemberAttribute.Value : value.ToString()); + } +} \ No newline at end of file diff --git a/Mindbox.YandexTracker/JsonConverters/QueueLocalFieldTypeConverter.cs b/Mindbox.YandexTracker/JsonConverters/QueueLocalFieldTypeConverter.cs deleted file mode 100644 index 1f52f23..0000000 --- a/Mindbox.YandexTracker/JsonConverters/QueueLocalFieldTypeConverter.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Reflection; -using System.Runtime.Serialization; -using System.Text.Json; -using System.Text.Json.Serialization; - -namespace Mindbox.YandexTracker.JsonConverters; - -public class QueueLocalFieldTypeConverter : JsonConverter -{ - public override QueueLocalFieldType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - string? enumString = reader.GetString(); - foreach (var field in typeToConvert.GetFields()) - { - if (field.GetCustomAttribute()?.Value == enumString) - { - return (QueueLocalFieldType)field.GetValue(null)!; - } - } - - if (enumString == null) throw new JsonException($"Unknown value for {nameof(QueueLocalFieldType)} ({enumString})"); - - return (QueueLocalFieldType)Enum.Parse(typeToConvert, enumString, true); - } - - public override void Write(Utf8JsonWriter writer, QueueLocalFieldType value, JsonSerializerOptions options) - { - var enumMemberAttribute = value.GetType().GetField(value.ToString())?.GetCustomAttribute(); - writer.WriteStringValue(enumMemberAttribute != null ? enumMemberAttribute.Value : value.ToString()); - } -} \ No newline at end of file diff --git a/Mindbox.YandexTracker/JsonConverters/YandexDateTimeConverter.cs b/Mindbox.YandexTracker/JsonConverters/YandexDateTimeJsonConverter.cs similarity index 78% rename from Mindbox.YandexTracker/JsonConverters/YandexDateTimeConverter.cs rename to Mindbox.YandexTracker/JsonConverters/YandexDateTimeJsonConverter.cs index f99ff05..a1d3632 100644 --- a/Mindbox.YandexTracker/JsonConverters/YandexDateTimeConverter.cs +++ b/Mindbox.YandexTracker/JsonConverters/YandexDateTimeJsonConverter.cs @@ -5,7 +5,10 @@ namespace Mindbox.YandexTracker.JsonConverters; -internal class YandexDateTimeConverter : JsonConverter +/// +/// Кастомный конвертер для сериализации/десериализации даты и времени в формате Yandex'а. +/// +internal class YandexDateTimeJsonConverter : JsonConverter { private const string DateFormat = "yyyy-MM-ddTHH:mm:ss.fffzzz"; // Adjust this to match your JSON date format diff --git a/Mindbox.YandexTracker/JsonConverters/YandexNullableDateTimeConverter.cs b/Mindbox.YandexTracker/JsonConverters/YandexNullableDateTimeJsonConverter.cs similarity index 78% rename from Mindbox.YandexTracker/JsonConverters/YandexNullableDateTimeConverter.cs rename to Mindbox.YandexTracker/JsonConverters/YandexNullableDateTimeJsonConverter.cs index 5557abb..8d6a4f7 100644 --- a/Mindbox.YandexTracker/JsonConverters/YandexNullableDateTimeConverter.cs +++ b/Mindbox.YandexTracker/JsonConverters/YandexNullableDateTimeJsonConverter.cs @@ -5,7 +5,10 @@ namespace Mindbox.YandexTracker.JsonConverters; -internal class YandexNullableDateTimeConverter : JsonConverter +/// +/// Кастомный конвертер для сериализации/десериализации nullable даты и времени в формате Yandex'а. +/// +internal class YandexNullableDateTimeJsonConverter : JsonConverter { private const string DateFormat = "yyyy-MM-ddTHH:mm:ss.fffzzz"; // Adjust this to match your JSON date format diff --git a/Mindbox.YandexTracker/YandexTrackerClient.cs b/Mindbox.YandexTracker/YandexTrackerClient.cs index b1f268f..39fe9ae 100644 --- a/Mindbox.YandexTracker/YandexTrackerClient.cs +++ b/Mindbox.YandexTracker/YandexTrackerClient.cs @@ -37,10 +37,10 @@ public YandexTrackerClient( { Converters = { - new QueueLocalFieldTypeConverter(), + new EnumWithEnumMemberAttributeJsonConverter(), new JsonStringEnumConverter(namingPolicy: JsonNamingPolicy.CamelCase), - new YandexDateTimeConverter(), - new YandexNullableDateTimeConverter() + new YandexDateTimeJsonConverter(), + new YandexNullableDateTimeJsonConverter() }, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, PropertyNamingPolicy = JsonNamingPolicy.CamelCase,