using System.Text.Json; using Models; namespace Repository; public class JsonRepository : IRepository { private const string _fileName = "data.json"; public User? Read() { if (File.Exists(_fileName)) { try { string json = File.ReadAllText(_fileName); return JsonSerializer.Deserialize(json) ?? new User("fallback", "fallback", "fallback"); } catch (JsonException e) { WriteToStdErr($"JSON error: {e.Message}"); } catch (IOException e) { WriteToStdErr($"File I/O error: {e.Message}"); } catch (Exception e) { WriteToStdErr($"Unexpected error: {e.Message}"); } } return null; } public int Write(User item) { try { string json = JsonSerializer.Serialize(item); File.WriteAllText(_fileName, json); return 0; } catch (JsonException e) { WriteToStdErr($"JSON error: {e.Message}"); return e.GetHashCode(); } catch (IOException e) { WriteToStdErr($"File I/O error: {e.Message}"); return e.GetHashCode(); } catch (Exception e) { WriteToStdErr($"Unexpected error: {e.Message}"); return e.GetHashCode(); } } private void WriteToStdErr(string message) { using var sw = new StreamWriter(Console.OpenStandardError()); sw.WriteLine(message); } }