index.ts 9.4 KB

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