hermes-server/Store/UserStore.cs

94 lines
3.0 KiB
C#
Raw Normal View History

using HermesSocketLibrary.db;
using HermesSocketServer.Models;
namespace HermesSocketServer.Store
{
public class UserStore : GroupSaveStore<string, User>
{
private readonly Database _database;
private readonly Serilog.ILogger _logger;
private readonly GroupSaveSqlGenerator<User> _generator;
public UserStore(Database database, Serilog.ILogger logger) : base(logger)
{
_database = database;
_logger = logger;
var ctp = new Dictionary<string, string>
{
{ "id", "Id" },
{ "name", "Name" },
{ "email", "Email" },
{ "role", "Role" },
{ "ttsDefaultVoice", "DefaultVoice" }
};
_generator = new GroupSaveSqlGenerator<User>(ctp);
}
public override async Task Load()
{
string sql = "SELECT id, name, email, role, \"ttsDefaultVoice\" FROM \"User\";";
await _database.Execute(sql, new Dictionary<string, object>(), (reader) =>
{
string id = reader.GetString(0);
_store.Add(id, new User()
{
Id = id,
Name = reader.GetString(1),
Email = reader.GetString(2),
Role = reader.GetString(3),
DefaultVoice = reader.GetString(4),
});
});
_logger.Information($"Loaded {_store.Count} users from database.");
}
public override void OnInitialAdd(string key, User value)
{
}
public override void OnInitialModify(string key, User value)
{
}
public override void OnInitialRemove(string key)
{
}
public override async Task<bool> Save()
{
if (_added.Any())
{
string sql = string.Empty;
lock (_lock)
{
sql = _generator.GenerateInsertSql("User", _added.Select(a => _store[a]), ["id", "name", "email", "role", "ttsDefaultVoice"]);
_added.Clear();
}
await _database.ExecuteScalar(sql);
}
if (_modified.Any())
{
string sql = string.Empty;
lock (_lock)
{
sql = _generator.GenerateUpdateSql("User", _modified.Select(m => _store[m]), ["id"], ["name", "email", "role", "ttsDefaultVoice"]);
_modified.Clear();
}
await _database.ExecuteScalar(sql);
}
if (_deleted.Any())
{
string sql = string.Empty;
lock (_lock)
{
sql = _generator.GenerateDeleteSql("User", _deleted, ["id"]);
_deleted.Clear();
}
await _database.ExecuteScalar(sql);
}
return true;
}
}
}