using System.Text.Json; using Journal.Core.Dtos; using Journal.Core.Models; using Journal.Core.Services; namespace Journal.Core; public class Entry { private readonly IFragmentService _fragments; public Entry(IFragmentService fragments) => _fragments = fragments; public async Task RunAsync() { string? line; while ((line = Console.ReadLine()) is not null) { var response = await HandleCommand(line); Console.WriteLine(response); } } private async Task HandleCommand(string json) { try { var cmd = JsonSerializer.Deserialize(json); if (cmd is null) return Error("Invalid command"); object? result = cmd.Action switch { "fragments.list" => await _fragments.GetAllAsync(), "fragments.get" => await _fragments.GetByIdAsync(Guid.Parse(cmd.Id!)), "fragments.create" => await _fragments.CreateAsync( cmd.Payload!.Value.Deserialize()!), "fragments.update" => await _fragments.UpdateAsync( Guid.Parse(cmd.Id!), cmd.Payload!.Value.Deserialize()!), "fragments.delete" => await _fragments.RemoveAsync(Guid.Parse(cmd.Id!)), "fragments.search" => await _fragments.SearchAsync(cmd.Type, cmd.Tag), _ => null }; if (result is null) return Error($"Unknown action: {cmd.Action}"); return JsonSerializer.Serialize(new { ok = true, data = result }); } catch (Exception ex) { return Error(ex.Message); } } private static string Error(string message) => JsonSerializer.Serialize(new { ok = false, error = message }); }