chaosbot/ChaosBot/ConfigHelpers/ConfigurationRepository.cs

58 lines
2.2 KiB
C#

using System.Linq;
using System.Threading.Tasks;
using ChaosBot.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace ChaosBot.ConfigHelpers
{
internal static class ConfigurationRepository
{
public static T GetValue<T>(string key, ulong guildId)
{
return GetValue<T>(key, guildId, default);
}
public static T GetValue<T>(string key, ulong guildId, T defaultValue)
{
using DatabaseContext dbContext = new DatabaseContext();
Models.Configuration config = dbContext.Configuration
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
if (config == null || string.IsNullOrEmpty(config.SerializedValue))
return GetValueFromAppSettings(key, guildId, defaultValue);
return JsonSerializer.Deserialize<T>(config.SerializedValue);
}
public static void SetValue<T>(string key, T value, ulong guildId)
{
using DatabaseContext dbContext = new DatabaseContext();
Models.Configuration cnfSet = new Models.Configuration();
cnfSet.Key = key;
cnfSet.DiscordGuildId = guildId;
cnfSet.SerializedValue = JsonConvert.SerializeObject(value);
dbContext.Configuration.Upsert(cnfSet)
.On(x => new {x.Key, x.DiscordGuildId})
.Run();
}
public static void DeleteValue(string key, ulong guildId)
{
using DatabaseContext dbContext = new DatabaseContext();
Models.Configuration config = dbContext.Configuration
.SingleOrDefault(c => c.DiscordGuildId == guildId && c.Key == key);
if (config == null) return;
dbContext.Remove(config);
dbContext.SaveChanges();
}
private static T GetValueFromAppSettings<T>(string key, ulong guildId, T defaultValue)
{
return Program.AppSettingsHandler.GetValue($"Servers:{guildId}:{key}", Program.AppSettingsHandler.GetValue(key, defaultValue));
}
}
}