DefaultApiRepository.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using Wicture.DbRESTFul.Infrastructure.Repository;
  8. using Wicture.DbRESTFul.PMT.Models;
  9. using Wicture.DbRESTFul.PMT.Scaffolding;
  10. namespace Wicture.DbRESTFul.PMT.Repositories
  11. {
  12. public class DefaultApiRepository : DbRESTFulRepository
  13. {
  14. public async Task<object> CheckExistName(JToken param)
  15. {
  16. var apiData = param["apiData"].ToObject<List<ACIData>>();
  17. var tableName = string.Join("-", apiData.Select(s => s.TableName).Distinct().ToArray());
  18. var methods = param.Value<JArray>("selectedMethods").ToObject<List<Methods>>();
  19. List<string> apiNames = new List<string>();
  20. foreach (var item in methods)
  21. {
  22. apiNames.Add($"{item.Title.ToString()}_{tableName}");
  23. }
  24. return await base.InvokeAsync("CheckAPINames", new { apiNames, projectId = param.Value<int>("projectId") });
  25. }
  26. public object LoadTablesForProject(JToken param)
  27. {
  28. string connectionString = param.Value<string>("connectionString");
  29. int projectId = param.Value<int>("projectId");
  30. var helper = new ScaffoldingHelper(connectionString, projectId);
  31. var table = helper.ListTables().Select(t => new { title = t.name, key = 1, children = t.columns });
  32. return table;
  33. }
  34. public async Task<object> CreateApis(JToken param)
  35. {
  36. var projectId = param.Value<int>("projectId");
  37. var methods = param.Value<JArray>("selectedMethods").ToObject<List<Methods>>();
  38. var module = param["module"].ToObject<Module>();
  39. var apiData = param["apiData"].ToObject<List<ACIData>>();
  40. var helper = new ScaffoldingHelper(param.Value<string>("connectionString"), param.Value<int>("projectId"));
  41. var tableNames = apiData.Select(s => s.TableName).Distinct().ToArray();
  42. var columNames = apiData.Where(w => w.TableName == "").Select(s => s.ColumnName);
  43. var tables = helper.ListTables().Where(w => (tableNames.Contains(w.name)));
  44. List<DefaultACIColumn> allColumns = new List<DefaultACIColumn>();
  45. tables.ForEach(f =>
  46. {
  47. var columns = new List<DefaultACIColumn>();
  48. f.columns.ForEach(cf =>
  49. {
  50. if (apiData.Where(w => w.TableName == f.name).Select(s => s.ColumnName).Contains(cf.name))
  51. columns.Add(cf);
  52. });
  53. allColumns.AddRange(columns);
  54. });
  55. using (var cnn = ConnectionManager.GetConnection(false))
  56. {
  57. cnn.Open();
  58. var transaction = cnn.BeginTransaction();
  59. try
  60. {
  61. foreach (var item in methods)
  62. {
  63. var data = this.ParamIntegration(projectId, module, item.Title, string.Join("-", tableNames), allColumns);
  64. await base.InvokeAsync("DeleteAndCreateApi", data, cnn, transaction);
  65. }
  66. transaction.Commit();
  67. }
  68. catch (Exception)
  69. {
  70. transaction.Rollback();
  71. throw;
  72. }
  73. }
  74. return null;
  75. }
  76. #region Private Methods
  77. private object ParamIntegration(int projectId, Module module, Method method, string tableName, List<DefaultACIColumn> columns)
  78. {
  79. ApiCreateData result = new ApiCreateData();
  80. switch (method)
  81. {
  82. case Method.Get:
  83. {
  84. result.method = "GET";
  85. result.module = module.ModuleName;
  86. result.moduleId = module.ModuleId;
  87. result.Name = $"Get_{tableName}";
  88. result.parameter = JsonConvert.SerializeObject(new { query = DefaultApiColumnToParameter(columns.Where(w => (w.primary_key))), body = new object[] { } });
  89. result.result = DefaultGetReturnApi(DefaultApiColumnToParameter(columns));
  90. result.url = $"{tableName.ToLower()}/get";
  91. result.projectId = projectId;
  92. result.title = $"获取详情:{tableName}";
  93. }
  94. break;
  95. case Method.List:
  96. {
  97. result.method = "GET";
  98. result.module = module.ModuleName;
  99. result.moduleId = module.ModuleId;
  100. result.Name = $"List_{tableName}";
  101. result.parameter = "{\"query\":[{\"name\":\"pageSize\",\"type\":\"int\",\"nullable\":false,\"description\":\"页数\"},{\"name\":\"pageIndex\",\"type\":\"int\",\"nullable\":false,\"description\":\"页码\"}],\"body\":[]}";
  102. result.result = DefaultListReturnApi(DefaultApiColumnToParameter(columns));
  103. result.url = $"{tableName.ToLower()}/list";
  104. result.projectId = projectId;
  105. result.title = $"获取列表:{tableName}";
  106. }
  107. break;
  108. case Method.Create:
  109. {
  110. result.method = "POST";
  111. result.module = module.ModuleName;
  112. result.moduleId = module.ModuleId;
  113. result.Name = $"Create_{tableName}";
  114. result.parameter = JsonConvert.SerializeObject(new { query = new object[] { }, body = DefaultApiColumnToParameter(columns) });
  115. result.result = DefaultGetReturnApi(new object[] { new { name = "id", type = "int", nullable = true, description = "返回创建编号" } });
  116. result.url = $"{tableName.ToLower()}/create";
  117. result.projectId = projectId;
  118. result.title = $"创建:{tableName}";
  119. }
  120. break;
  121. case Method.Update:
  122. {
  123. result.method = "PUT";
  124. result.module = module.ModuleName;
  125. result.moduleId = module.ModuleId;
  126. result.Name = $"Update_{tableName}";
  127. result.parameter = JsonConvert.SerializeObject(new { query = new object[] { }, body = DefaultApiColumnToParameter(columns) });
  128. result.result = DefaultGetReturnApi(new object[] { new { name = "count", type = "int", nullable = true, description = "更新数量" } });
  129. result.url = $"{tableName.ToLower()}/update";
  130. result.projectId = projectId;
  131. result.title = $"更新:{tableName}";
  132. }
  133. break;
  134. case Method.Delete:
  135. {
  136. result.method = "DELETE";
  137. result.module = module.ModuleName;
  138. result.moduleId = module.ModuleId;
  139. result.Name = $"Delete_{tableName}";
  140. result.parameter = JsonConvert.SerializeObject(new { query = DefaultApiColumnToParameter(columns.Where(w => (w.primary_key))), body = new object[] { } });
  141. result.result = DefaultGetReturnApi(new object[] { new { name = "count", type = "int", nullable = true, description = "删除数量" } });
  142. result.url = $"{tableName.ToLower()}/delete";
  143. result.projectId = projectId;
  144. result.title = $"删除:{tableName}";
  145. }
  146. break;
  147. }
  148. result.implementation = "{\"type\":\"csi\",\"name\":\"" + result.Name + "\"}";
  149. result.summary = result.title;
  150. result.deprecated = false;
  151. result.protocol = "HttpAndRpc";
  152. return result;
  153. }
  154. private IEnumerable<Parameter> DefaultApiColumnToParameter(IEnumerable<DefaultACIColumn> columns)
  155. {
  156. foreach (var item in columns)
  157. {
  158. yield return new Parameter
  159. {
  160. name = item.name,
  161. type = TransferType(item.type),
  162. nullable = item.nullable,
  163. description = item.description
  164. };
  165. }
  166. }
  167. /// <summary>
  168. /// 根据查询类型转换目前支持类型
  169. /// </summary>
  170. /// <param name="type"></param>
  171. /// <returns></returns>
  172. private string TransferType(string type)
  173. {
  174. var result = type;
  175. if (type.Contains("char") || type.Contains("uniqueidentifier") || type.Contains("text"))
  176. {
  177. result = "string";
  178. }
  179. if (type.Contains("int"))
  180. {
  181. result = "int";
  182. }
  183. if (type.Contains("decimal") || type.Contains("double"))
  184. {
  185. result = "decimal";
  186. }
  187. if (type.Contains("bit"))
  188. {
  189. result = "bit";
  190. }
  191. if (result != "object" && result != "array" && result != "string" && result != "int" && result != "bool" && result != "decimal" && result != "number" && result != "datetime" && result != "bit")
  192. {
  193. result = "object";
  194. }
  195. return result;
  196. }
  197. private string DefaultGetReturnApi(object schemaObj)
  198. {
  199. return JsonConvert.SerializeObject(new
  200. {
  201. type = "json",
  202. schema = new object[]{
  203. new { name = "statusCode", type = "int", nullable = false, description = "错误码(默认为200,无错误信息)" },
  204. new { name = "errorMessage", type = "string", nullable = true, description = "错误信息" },
  205. new { name = "data", type = "object", nullable = true, description = "接口信息数据集", schema = schemaObj }
  206. }
  207. });
  208. }
  209. private string DefaultListReturnApi(object schemaObj)
  210. {
  211. return DefaultGetReturnApi(
  212. new object[]
  213. {
  214. new { name = "items", type = "array", nullable = false, description = "数据集", schema = schemaObj },
  215. new { name = "pagination", type = "object", nullable = false, description = "分页数据",
  216. schema = new object[]
  217. {
  218. new { name = "totalCount", type = "int", nullable = false, description = "总条数" },
  219. new { name = "pageSize", type = "int", nullable = false, description = "页数" },
  220. new { name = "pageIndex", type = "int", nullable = false, description = "页码" }
  221. }
  222. }
  223. });
  224. }
  225. #endregion
  226. }
  227. }