Files
qhmes/yy-admin-master/YY.Admin.Services/Service/Config/SysConfigService.cs

103 lines
3.6 KiB
C#
Raw Normal View History

using SqlSugar;
using YY.Admin.Core;
using YY.Admin.Core.Const;
using YY.Admin.Core.SeedData;
namespace YY.Admin.Services.Service.Config
{
public class SysConfigService : ISysConfigService, ISingletonDependency
{
private readonly ISysCacheService _sysCacheService;
private readonly ISqlSugarClient _dbContext;
public SysConfigService(
ISysCacheService sysCacheService,
ISqlSugarClient dbContext)
{
_sysCacheService= sysCacheService;
_dbContext= dbContext;
}
public async Task<T> GetConfigValue<T>(string code)
{
if (string.IsNullOrWhiteSpace(code)) return default;
var value = _sysCacheService.Get<string>($"{CacheConst.KeyConfig}{code}");
if (string.IsNullOrEmpty(value))
{
value = (await _dbContext.Queryable<SysConfig>().FirstAsync(u => u.Code == code))?.Value;
_sysCacheService.Set($"{CacheConst.KeyConfig}{code}", value);
}
if (string.IsNullOrWhiteSpace(value)) return default;
// boolConvert.ChangeType 对 "1"/"Y" 等会抛异常,统一稳健解析
var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
if (targetType == typeof(bool))
{
var b = ParseConfigBool(value);
return (T)(object)b;
}
return (T)Convert.ChangeType(value, targetType);
}
private static bool ParseConfigBool(string value)
{
if (bool.TryParse(value, out var b))
return b;
switch (value.Trim().ToLowerInvariant())
{
case "1":
case "y":
case "yes":
case "on":
return true;
case "0":
case "n":
case "no":
case "off":
return false;
default:
return false;
}
}
/// <inheritdoc />
public async Task<(bool ok, string message)> SetConfigValueAsync(string code, string value)
{
if (string.IsNullOrWhiteSpace(code))
return (false, "配置编码无效");
var n = await _dbContext.Updateable<SysConfig>()
.SetColumns(c => new SysConfig { Value = value, UpdateTime = DateTime.Now })
.Where(c => c.Code == code)
.ExecuteCommandAsync();
if (n <= 0)
{
// 旧库可能缺少新增配置项,按种子模板补插后再写入
var seed = new SysConfigSeedData().HasData()
.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase));
if (seed == null)
return (false, "未找到对应配置项或无需更新");
var row = new SysConfig
{
Id = seed.Id,
Name = seed.Name,
Code = seed.Code,
Value = value,
SysFlag = seed.SysFlag,
GroupCode = seed.GroupCode,
OrderNo = seed.OrderNo,
Remark = seed.Remark,
CreateTime = DateTime.Now,
UpdateTime = DateTime.Now,
};
await _dbContext.Insertable(row).ExecuteCommandAsync();
}
_sysCacheService.Remove($"{CacheConst.KeyConfig}{code}");
return (true, "保存成功");
}
}
}