61 lines
1.5 KiB
C#
61 lines
1.5 KiB
C#
|
|
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);
|
|||
|
|
}
|
|||
|
|
}
|