First commit

This commit is contained in:
2025-09-26 17:32:32 +02:00
commit 6c5579809d
14 changed files with 417 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
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<User>(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 void Write(User item)
{
try
{
string json = JsonSerializer.Serialize(item);
File.WriteAllText(_fileName, json);
}
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}");
}
}
private void WriteToStdErr(string message)
{
using var sw = new StreamWriter(Console.OpenStandardError());
sw.WriteLine(message);
}
}