index.ts 8.4 KB

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