index.ts 8.6 KB

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