using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.Response;
using OpenAuth.Repository.Core;
using SqlSugar;
namespace OpenAuth.App
{
///
/// 动态API应用层
/// 用于处理任意实体的CRUD操作
///
public class DynamicApiApp
{
private readonly ISqlSugarClient _client;
private readonly IAuth _auth;
public DynamicApiApp(ISqlSugarClient client, IAuth auth)
{
_client = client;
_auth = auth;
}
///
/// 获取实体列表
///
/// 实体名称,例如:ExternalDataSource
/// 页码
/// 每页记录数
/// 搜索关键字
///
public async Task GetList(string entityName, int page = 1, int limit = 10, string key = "")
{
var result = new TableData();
try
{
// 获取实体类型
var entityType = GetEntityType(entityName);
if (entityType == null)
{
result.code = 500;
result.msg = $"未找到实体:{entityName}";
return result;
}
// 创建动态查询
dynamic queryable = _client.GetType().GetMethod("Queryable", new Type[] { })
.MakeGenericMethod(entityType)
.Invoke(_client, null);
// 如果有搜索关键字,尝试在常见字段中搜索
if (!string.IsNullOrEmpty(key))
{
// 获取实体的所有属性
var properties = entityType.GetProperties();
// 尝试在Name、Title等常见字段中搜索
var nameProperty = properties.FirstOrDefault(p =>
p.Name.Equals("Name", StringComparison.OrdinalIgnoreCase));
if (nameProperty != null)
{
queryable = queryable.Where($"{nameProperty.Name} like @key", new { key = $"%{key}%" });
}
}
// 获取总记录数
var total = await queryable.CountAsync();
// 分页查询
var list = await queryable.OrderBy("CreateTime DESC")
.Skip((page - 1) * limit)
.Take(limit)
.ToListAsync();
result.data = list;
result.count = total;
}
catch (Exception ex)
{
result.code = 500;
result.msg = ex.InnerException?.Message ?? ex.Message;
}
return result;
}
///
/// 获取实体详情
///
/// 实体名称,例如:ExternalDataSource
/// 实体ID
///
public Response