using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Wicture.DbRESTFul.Infrastructure.Repository; using Wicture.DbRESTFul.PMT.Models; using Wicture.DbRESTFul.PMT.Scaffolding; namespace Wicture.DbRESTFul.PMT.Repositories { public class DefaultApiRepository : DbRESTFulRepository { public async Task CheckExistName(JToken param) { var apiData = param["apiData"].ToObject>(); var tableName = string.Join("-", apiData.Select(s => s.TableName).Distinct().ToArray()); var methods = param.Value("selectedMethods").ToObject>(); List apiNames = new List(); foreach (var item in methods) { apiNames.Add($"{item.Title.ToString()}_{tableName}"); } return await base.InvokeAsync("CheckAPINames", new { apiNames, projectId = param.Value("projectId") }); } public object LoadTablesForProject(JToken param) { string connectionString = param.Value("connectionString"); int projectId = param.Value("projectId"); var helper = new ScaffoldingHelper(connectionString, projectId); var table = helper.ListTables().Select(t => new { title = t.name, key = 1, children = t.columns }); return table; } public async Task CreateApis(JToken param) { var projectId = param.Value("projectId"); var methods = param.Value("selectedMethods").ToObject>(); var module = param["module"].ToObject(); var apiData = param["apiData"].ToObject>(); var helper = new ScaffoldingHelper(param.Value("connectionString"), param.Value("projectId")); var tableNames = apiData.Select(s => s.TableName).Distinct().ToArray(); var columNames = apiData.Where(w => w.TableName == "").Select(s => s.ColumnName); var tables = helper.ListTables().Where(w => (tableNames.Contains(w.name))); List allColumns = new List(); tables.ForEach(f => { var columns = new List(); f.columns.ForEach(cf => { if (apiData.Where(w => w.TableName == f.name).Select(s => s.ColumnName).Contains(cf.name)) columns.Add(cf); }); allColumns.AddRange(columns); }); using (var cnn = ConnectionManager.GetConnection(false)) { cnn.Open(); var transaction = cnn.BeginTransaction(); try { foreach (var item in methods) { var data = this.ParamIntegration(projectId, module, item.Title, string.Join("-", tableNames), allColumns); await base.InvokeAsync("DeleteAndCreateApi", data, cnn, transaction); } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } } return null; } #region Private Methods private object ParamIntegration(int projectId, Module module, Method method, string tableName, List columns) { ApiCreateData result = new ApiCreateData(); switch (method) { case Method.Get: { result.method = "GET"; result.module = module.ModuleName; result.moduleId = module.ModuleId; result.Name = $"Get_{tableName}"; result.parameter = JsonConvert.SerializeObject(new { query = DefaultApiColumnToParameter(columns.Where(w => (w.primary_key))), body = new object[] { } }); result.result = DefaultGetReturnApi(DefaultApiColumnToParameter(columns)); result.url = $"{tableName.ToLower()}/get"; result.projectId = projectId; result.title = $"获取详情:{tableName}"; } break; case Method.List: { result.method = "GET"; result.module = module.ModuleName; result.moduleId = module.ModuleId; result.Name = $"List_{tableName}"; result.parameter = "{\"query\":[{\"name\":\"pageSize\",\"type\":\"int\",\"nullable\":false,\"description\":\"页数\"},{\"name\":\"pageIndex\",\"type\":\"int\",\"nullable\":false,\"description\":\"页码\"}],\"body\":[]}"; result.result = DefaultListReturnApi(DefaultApiColumnToParameter(columns)); result.url = $"{tableName.ToLower()}/list"; result.projectId = projectId; result.title = $"获取列表:{tableName}"; } break; case Method.Create: { result.method = "POST"; result.module = module.ModuleName; result.moduleId = module.ModuleId; result.Name = $"Create_{tableName}"; result.parameter = JsonConvert.SerializeObject(new { query = new object[] { }, body = DefaultApiColumnToParameter(columns) }); result.result = DefaultGetReturnApi(new object[] { new { name = "id", type = "int", nullable = true, description = "返回创建编号" } }); result.url = $"{tableName.ToLower()}/create"; result.projectId = projectId; result.title = $"创建:{tableName}"; } break; case Method.Update: { result.method = "PUT"; result.module = module.ModuleName; result.moduleId = module.ModuleId; result.Name = $"Update_{tableName}"; result.parameter = JsonConvert.SerializeObject(new { query = new object[] { }, body = DefaultApiColumnToParameter(columns) }); result.result = DefaultGetReturnApi(new object[] { new { name = "count", type = "int", nullable = true, description = "更新数量" } }); result.url = $"{tableName.ToLower()}/update"; result.projectId = projectId; result.title = $"更新:{tableName}"; } break; case Method.Delete: { result.method = "DELETE"; result.module = module.ModuleName; result.moduleId = module.ModuleId; result.Name = $"Delete_{tableName}"; result.parameter = JsonConvert.SerializeObject(new { query = DefaultApiColumnToParameter(columns.Where(w => (w.primary_key))), body = new object[] { } }); result.result = DefaultGetReturnApi(new object[] { new { name = "count", type = "int", nullable = true, description = "删除数量" } }); result.url = $"{tableName.ToLower()}/delete"; result.projectId = projectId; result.title = $"删除:{tableName}"; } break; } result.implementation = "{\"type\":\"csi\",\"name\":\"" + result.Name + "\"}"; result.summary = result.title; result.deprecated = false; result.protocol = "HttpAndRpc"; return result; } private IEnumerable DefaultApiColumnToParameter(IEnumerable columns) { foreach (var item in columns) { yield return new Parameter { name = item.name, type = TransferType(item.type), nullable = item.nullable, description = item.description }; } } /// /// 根据查询类型转换目前支持类型 /// /// /// private string TransferType(string type) { var result = type; if (type.Contains("char") || type.Contains("uniqueidentifier") || type.Contains("text")) { result = "string"; } if (type.Contains("int")) { result = "int"; } if (type.Contains("decimal") || type.Contains("double")) { result = "decimal"; } if (type.Contains("bit")) { result = "bit"; } if (result != "object" && result != "array" && result != "string" && result != "int" && result != "bool" && result != "decimal" && result != "number" && result != "datetime" && result != "bit") { result = "object"; } return result; } private string DefaultGetReturnApi(object schemaObj) { return JsonConvert.SerializeObject(new { type = "json", schema = new object[]{ new { name = "statusCode", type = "int", nullable = false, description = "错误码(默认为200,无错误信息)" }, new { name = "errorMessage", type = "string", nullable = true, description = "错误信息" }, new { name = "data", type = "object", nullable = true, description = "接口信息数据集", schema = schemaObj } } }); } private string DefaultListReturnApi(object schemaObj) { return DefaultGetReturnApi( new object[] { new { name = "items", type = "array", nullable = false, description = "数据集", schema = schemaObj }, new { name = "pagination", type = "object", nullable = false, description = "分页数据", schema = new object[] { new { name = "totalCount", type = "int", nullable = false, description = "总条数" }, new { name = "pageSize", type = "int", nullable = false, description = "页数" }, new { name = "pageIndex", type = "int", nullable = false, description = "页码" } } } }); } #endregion } }