JsonDB/IO/LocalStore.cs
2024-08-12 12:46:55 +09:00

98 lines
2.2 KiB
C#

using System.Text;
using System.Text.Json;
namespace DevJsonDB.IO;
public class LocalStore<T> : IStore<T>
{
private static Encoding DefaultEncoding = Encoding.UTF8;
private string filePath;
private List<T> items;
public LocalStore(string filePath)
{
this.filePath = filePath;
this.items = new List<T>();
this.InitDatabase();
}
public void Dispose()
{
this.Commit();
}
public void Commit()
{
try
{
using (FileStream fs = new FileStream(this.filePath, FileMode.OpenOrCreate))
using (StreamWriter writer = new StreamWriter(fs, DefaultEncoding))
{
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
foreach (T item in this.items)
{
string json = JsonSerializer.Serialize<T>(item);
writer.WriteLine(json);
}
}
}
catch (Exception ex)
{
throw new JsonDBException(ex.Message, ex);
}
}
public bool Add(T item)
{
if (this.items.Contains(item))
{
return false;
}
this.items.Add(item);
return true;
}
public bool Has(T item)
{
return this.items.Contains(item);
}
public bool Remove(T item)
{
return this.items.Remove(item);
}
public IEnumerable<T> GetValues()
{
return this.items.ToList();
}
private void InitDatabase()
{
try
{
using (FileStream fs = new FileStream(this.filePath, FileMode.OpenOrCreate))
using (StreamReader reader = new StreamReader(fs, DefaultEncoding))
{
string? line = null;
while ((line = reader.ReadLine()) != null)
{
T? value = JsonSerializer.Deserialize<T>(line);
if (value is object)
{
this.items.Add(value);
}
}
}
}
catch (Exception ex)
{
throw new JsonDBException(ex.Message, ex);
}
}
}