First commit
This commit is contained in:
61
Repository/JsonRepository.cs
Normal file
61
Repository/JsonRepository.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user