chaosbot/ChaosBot/Repositories/ConfigurationRepository.cs

45 lines
1.6 KiB
C#

using System;
using System.Linq;
using ChaosBot.Models;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
namespace ChaosBot.Repositories
{
public 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 (ChaosbotContext dbContext = new ChaosbotContext())
{
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 DeleteValue(string key, ulong guildId)
{
using (ChaosbotContext dbContext = new ChaosbotContext())
{
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));
}
}
}