using System; using System.Net.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; // ReSharper disable CheckNamespace namespace BITKit // ReSharper restore CheckNamespace { public record ContextModel { public static ContextModel Get(object data) { return new ContextModel() { StatusCode = 200, Message = "success", Data = data }; } public static ContextModel Error(string message) { return new ContextModel() { StatusCode = 500, Message = message, Data = false }; } public static ContextModel GetFromJson(string json) { try { var result = new ContextModel(); var jObject = JObject.Parse(json); if(jObject.TryGetValue("status_code",out var statusCode)) result.StatusCode = statusCode.Value(); if(jObject.TryGetValue("message",out var message)) result.Message = message.Value(); if (jObject.TryGetValue("data", out var data)) result.Data = data; return JsonConvert.DeserializeObject(json); } catch (Exception e) { BIT4Log.Warning(json); throw; } } public static implicit operator string(ContextModel self) { return self.ToString(); } #if NET5_0_OR_GREATER public static implicit operator HttpContent(ContextModel self) { return new StringContent(self, System.Text.Encoding.UTF8, "application/json"); } #endif public override string ToString() { return JsonConvert.SerializeObject(this); } [JsonProperty("status_code")] public int StatusCode=200; [JsonProperty("message")] public string Message=string.Empty; [JsonProperty("data")] public object Data=string.Empty; [JsonIgnore] public bool IsSuccess => StatusCode is 200 or 0; public bool TryAs(out T value) { switch (Data) { case T t: value = t; return true; case JToken jToken: value = jToken.ToObject(); return true; default: value = default; return false; } } } }