using Microsoft.Extensions.Logging; using System.Text; namespace DigitalData.Core.DTO { public static class DTOExtensions { public static T Message(this T result, string message) where T : Result { result.Messages.Add(message); return result; } public static T Message(this T result, params string[] messages) where T : Result { result.Messages.AddRange(messages); return result; } public static T Notice(this T result, Notice notice) where T : Result { result.Notices.Add(notice); return result; } public static T Notice(this T result, params Notice[] notices) where T : Result { result.Notices.AddRange(notices); return result; } public static T Notice(this T result, LogLevel level, params Enum[] flags) where T : Result { var notices = flags.Select(flag => new Notice() { Flag = flag, Level = level }); result.Notices.AddRange(notices); return result; } public static T Notice(this T result, LogLevel level, Enum flag, params string[] messages) where T : Result { result.Notices.Add(new Notice() { Flag = flag, Level = level, Messages = messages.ToList() }); return result; } public static T Notice(this T result, LogLevel level, params string[] messages) where T : Result { result.Notices.Add(new Notice() { Flag = null, Level = level, Messages = messages.ToList() }); return result; } public static I Then(this Result result, Func Try, Func, List, I> Catch) { return result.IsSuccess ? Try() : Catch(result.Messages, result.Notices); } public static I Then(this DataResult result, Func Try, Func, List, I> Catch) { return result.IsSuccess ? Try(result.Data) : Catch(result.Messages, result.Notices); } public static async Task Then(this Task tResult, Func Try, Func, List, I> Catch) { Result result = await tResult; return result.IsSuccess ? Try() : Catch(result.Messages, result.Notices); } public static async Task Then(this Task> tResult, Func Try, Func, List, I> Catch) { DataResult result = await tResult; return result.IsSuccess ? Try(result.Data) : Catch(result.Messages, result.Notices); } public static void LogNotice(this ILogger logger, IEnumerable notices, string start = ": ", string seperator = ". ", string end = ".\n") { foreach(LogLevel level in Enum.GetValues(typeof(LogLevel))) { var logNotices = notices.Where(n => n.Level == level); if (!logNotices.Any()) continue; var sb = new StringBuilder(); foreach(Notice notice in logNotices) { if (notice.Flag is not null) sb.Append(notice.Flag); if (notice.Messages.Any()) sb.Append(start).Append(string.Join(seperator, notice.Messages)).AppendLine(end); else sb.Append(end); } logger.Log(level, sb.ToString()); } } } }