using System.Text; using EasyNetQ.Consumer; using Newtonsoft.Json; namespace adas_core.Infrastructure.Utils; /// /// Provides an implementation of tailored for use with RabbitMQ, responsible for serializing error messages into a format suitable for transport over RabbitMQ. /// /// /// This class serves as the RabbitMQ-specific concrete realization of the contract. /// public class RabbitIErrorMessageSerializer : IErrorMessageSerializer { /// /// Deserializes a JSON-encoded string by unescaping its JSON representation and converts the result to a UTF-8 byte array. /// Returns null when the deserialized string is null. /// /// The JSON-encoded string to unescape and convert. /// A UTF-8 encoded byte array of the unescaped string, or null if the deserialized value is null. public byte[]? Deserialize(string messageBody) { var unescapedJsonString = JsonConvert.DeserializeObject(messageBody); return unescapedJsonString != null ? Encoding.UTF8.GetBytes(unescapedJsonString) : null; } /// /// Attempts to deserialize the UTF-8 decoded message body as a JSON string, returning the original stringified content if deserialization fails. /// /// The raw byte array representing the message body to be deserialized. /// The deserialized JSON string if successful; otherwise, the raw UTF-8 decoded string. Returns if the deserialized JSON value is null. public string? Serialize(byte[] messageBody) { var stringifiedMsgBody = Encoding.UTF8.GetString(messageBody); try { return JsonConvert.DeserializeObject(stringifiedMsgBody); } catch (Exception) { return stringifiedMsgBody; } } }