index.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import { createDir, error, firstUpperCase, readFile, toCamel } from "../utils";
  2. import { join } from "path";
  3. import { Entity, DistPath } from "./config";
  4. import axios from "axios";
  5. import { isArray, isEmpty, last, merge } from "lodash";
  6. import { createWriteStream } from "fs";
  7. import prettier from "prettier";
  8. import { proxy } from "../../../src/config/proxy";
  9. import type { Eps } from "../types";
  10. // 获取方法名
  11. function getNames(v: any) {
  12. return Object.keys(v).filter((e) => !["namespace", "permission"].includes(e));
  13. }
  14. // 数据
  15. let service = {};
  16. let list: Eps.Entity[] = [];
  17. // 获取数据
  18. async function getData(temps?: Eps.Entity[]) {
  19. // 本地文件
  20. try {
  21. list = JSON.parse(readFile(join(DistPath, "eps.json")) || "[]");
  22. } catch (err: any) {
  23. error(`[eps] ${join(DistPath, "eps.json")} 文件异常, ${err.message}`);
  24. }
  25. // 远程地址
  26. const url = proxy["/dev/"].target + "/admin/base/open/eps";
  27. // 请求数据
  28. await axios
  29. .get(url, {
  30. timeout: 5000
  31. })
  32. .then((res) => {
  33. const { code, data, message } = res.data;
  34. if (code === 1000) {
  35. if (!isEmpty(data) && data) {
  36. list = Object.values(data).flat() as Eps.Entity[];
  37. }
  38. } else {
  39. error(`[eps] ${message}`);
  40. }
  41. })
  42. .catch(() => {
  43. error(`[eps] ${url} 服务未启动!!!`);
  44. });
  45. // 合并本地 service 数据
  46. if (isArray(temps)) {
  47. temps.forEach((e) => {
  48. const d = list.find((a) => e.prefix === a.prefix);
  49. if (d) {
  50. merge(d, e);
  51. } else {
  52. list.push(e);
  53. }
  54. });
  55. }
  56. }
  57. // 创建 json 文件
  58. function createJson() {
  59. const d = list.map((e) => {
  60. return {
  61. prefix: e.prefix,
  62. name: e.name || "",
  63. api: e.api.map((e) => {
  64. return {
  65. name: e.name,
  66. method: e.method,
  67. path: e.path
  68. };
  69. })
  70. };
  71. });
  72. createWriteStream(join(DistPath, "eps.json"), {
  73. flags: "w"
  74. }).write(JSON.stringify(d));
  75. }
  76. // 创建描述文件
  77. async function createDescribe({ list, service }: { list: Eps.Entity[]; service: any }) {
  78. // 获取类型
  79. function getType({ propertyName, type }: any) {
  80. for (const map of Entity.mapping) {
  81. if (map.custom) {
  82. const resType = map.custom({ propertyName, type });
  83. if (resType) return resType;
  84. }
  85. if (map.test) {
  86. if (map.test.includes(type)) return map.type;
  87. }
  88. }
  89. return type;
  90. }
  91. // 创建 Entity
  92. function createEntity() {
  93. const t0: string[][] = [];
  94. for (const item of list) {
  95. if (!item.name) continue;
  96. const t = [`interface ${item.name} {`];
  97. for (const col of item.columns || []) {
  98. // 描述
  99. t.push("\n");
  100. t.push("/**\n");
  101. t.push(` * ${col.comment}\n`);
  102. t.push(" */\n");
  103. t.push(
  104. `${col.propertyName}?: ${getType({
  105. propertyName: col.propertyName,
  106. type: col.type
  107. })};`
  108. );
  109. }
  110. t.push("\n");
  111. t.push("/**\n");
  112. t.push(` * 任意键值\n`);
  113. t.push(" */\n");
  114. t.push(`[key: string]: any;`);
  115. t.push("}");
  116. t0.push(t);
  117. }
  118. return t0.map((e) => e.join("")).join("\n\n");
  119. }
  120. // 创建 Service
  121. function createDts() {
  122. const t0: string[][] = [];
  123. const t1 = [
  124. `
  125. type json = any;
  126. type Service = {
  127. request(options?: {
  128. url: string;
  129. method?: "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
  130. data?: any;
  131. params?: any;
  132. headers?: {
  133. [key: string]: any;
  134. },
  135. timeout?: number;
  136. proxy?: boolean;
  137. [key: string]: any;
  138. }): Promise<any>;
  139. `
  140. ];
  141. // 处理数据
  142. function deep(d: any, k?: string) {
  143. if (!k) k = "";
  144. for (const i in d) {
  145. const name = k + toCamel(firstUpperCase(i.replace(/[:]/g, "")));
  146. if (d[i].namespace) {
  147. // 查找配置
  148. const item = list.find((e) => (e.prefix || "").includes(d[i].namespace));
  149. if (item) {
  150. const t = [`interface ${name} {`];
  151. t1.push(`${i}: ${name};`);
  152. // 插入方法
  153. if (item.api) {
  154. // 权限列表
  155. const permission: string[] = [];
  156. item.api.forEach((a) => {
  157. // 方法名
  158. const n = toCamel(a.name || last(a.path.split("/")) || "").replace(
  159. /[:\/-]/g,
  160. ""
  161. );
  162. if (n) {
  163. // 参数类型
  164. let q: string[] = [];
  165. // 参数列表
  166. const { parameters = [] } = a.dts || {};
  167. parameters.forEach((p) => {
  168. if (p.description) {
  169. q.push(`\n/** ${p.description} */\n`);
  170. }
  171. if (p.name.includes(":")) {
  172. return false;
  173. }
  174. const a = `${p.name}${p.required ? "" : "?"}`;
  175. const b = `${p.schema.type || "string"}`;
  176. q.push(`${a}: ${b},`);
  177. });
  178. if (isEmpty(q)) {
  179. q = ["any"];
  180. } else {
  181. q.unshift("{");
  182. q.push("}");
  183. }
  184. // 返回类型
  185. let res = "";
  186. // 实体名
  187. const en = item.name || "any";
  188. switch (a.path) {
  189. case "/page":
  190. res = `
  191. {
  192. pagination: { size: number; page: number; total: number; [key: string]: any };
  193. list: ${en} [];
  194. [key: string]: any;
  195. }
  196. `;
  197. break;
  198. case "/list":
  199. res = `${en} []`;
  200. break;
  201. case "/info":
  202. res = en;
  203. break;
  204. default:
  205. res = "any";
  206. break;
  207. }
  208. // 描述
  209. t.push("\n");
  210. t.push("/**\n");
  211. t.push(` * ${a.summary || n}\n`);
  212. t.push(" */\n");
  213. t.push(
  214. `${n}(data${q.length == 1 ? "?" : ""}: ${q.join(
  215. ""
  216. )}): Promise<${res}>;`
  217. );
  218. }
  219. permission.push(n);
  220. });
  221. // 权限标识
  222. t.push("\n");
  223. t.push("/**\n");
  224. t.push(" * 权限标识\n");
  225. t.push(" */\n");
  226. t.push(
  227. `permission: { ${permission
  228. .map((e) => `${e}: string;`)
  229. .join("\n")} };`
  230. );
  231. // 权限状态
  232. t.push("\n");
  233. t.push("/**\n");
  234. t.push(" * 权限状态\n");
  235. t.push(" */\n");
  236. t.push(
  237. `_permission: { ${permission
  238. .map((e) => `${e}: boolean;`)
  239. .join("\n")} };`
  240. );
  241. // 请求
  242. t.push("\n");
  243. t.push("/**\n");
  244. t.push(" * 请求\n");
  245. t.push(" */\n");
  246. t.push(`request: Service['request']`);
  247. }
  248. t.push("}");
  249. t0.push(t);
  250. }
  251. } else {
  252. t1.push(`${i}: {`);
  253. deep(d[i], name);
  254. t1.push(`},`);
  255. }
  256. }
  257. }
  258. // 深度
  259. deep(service);
  260. // 结束
  261. t1.push("}");
  262. // 追加
  263. t0.push(t1);
  264. return t0.map((e) => e.join("")).join("\n\n");
  265. }
  266. // 文件内容
  267. const text = `
  268. declare namespace Eps {
  269. ${createEntity()}
  270. ${createDts()}
  271. }
  272. `;
  273. // 文本内容
  274. const content = prettier.format(text, {
  275. parser: "typescript",
  276. useTabs: true,
  277. tabWidth: 4,
  278. endOfLine: "lf",
  279. semi: true,
  280. singleQuote: false,
  281. printWidth: 100,
  282. trailingComma: "none"
  283. });
  284. // 创建 eps 描述文件
  285. createWriteStream(join(DistPath, "eps.d.ts"), {
  286. flags: "w"
  287. }).write(content);
  288. }
  289. // 创建 service
  290. function createService() {
  291. list.forEach((e) => {
  292. // 分隔路径
  293. const arr = e.prefix
  294. .replace(/\//, "")
  295. .replace("admin", "")
  296. .split("/")
  297. .filter(Boolean)
  298. .map(toCamel);
  299. // 遍历
  300. function deep(d: any, i: number) {
  301. const k = arr[i];
  302. if (k) {
  303. // 是否最后一个
  304. if (arr[i + 1]) {
  305. if (!d[k]) {
  306. d[k] = {};
  307. }
  308. deep(d[k], i + 1);
  309. } else {
  310. // 不存在则创建
  311. if (!d[k]) {
  312. d[k] = {
  313. namespace: e.prefix.substring(1, e.prefix.length),
  314. permission: {}
  315. };
  316. }
  317. // 创建方法
  318. e.api.forEach((a) => {
  319. // 方法名
  320. const n = a.path.replace("/", "");
  321. if (n && !/[-:]/g.test(n)) {
  322. d[k][n] = a;
  323. }
  324. });
  325. // 创建权限
  326. getNames(d[k]).forEach((e) => {
  327. d[k].permission[e] = `${d[k].namespace.replace("admin/", "")}/${e}`.replace(
  328. /\//g,
  329. ":"
  330. );
  331. });
  332. }
  333. }
  334. }
  335. deep(service, 0);
  336. });
  337. }
  338. // 创建 eps
  339. export async function createEps(query?: { list: any[] }) {
  340. // 获取数据
  341. await getData(query?.list || []);
  342. // 创建 service
  343. createService();
  344. // 创建临时目录
  345. createDir(DistPath);
  346. // 创建 json 文件
  347. createJson();
  348. // 创建描述文件
  349. createDescribe({ service, list });
  350. return {
  351. service,
  352. list
  353. };
  354. }