优化 eps

This commit is contained in:
神仙 2024-10-13 00:12:45 +08:00
parent cf7309d6f5
commit 043a951f71
6 changed files with 1509 additions and 1285 deletions

View File

@ -1,8 +1,8 @@
(function (global, factory) { (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs'), require('path'), require('axios'), require('lodash'), require('prettier'), require('@vue/compiler-sfc'), require('magic-string'), require('glob'), require('svgo')) : typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('fs'), require('path'), require('axios'), require('lodash-es'), require('prettier'), require('@vue/compiler-sfc'), require('magic-string'), require('glob'), require('svgo')) :
typeof define === 'function' && define.amd ? define(['exports', 'fs', 'path', 'axios', 'lodash', 'prettier', '@vue/compiler-sfc', 'magic-string', 'glob', 'svgo'], factory) : typeof define === 'function' && define.amd ? define(['exports', 'fs', 'path', 'axios', 'lodash-es', 'prettier', '@vue/compiler-sfc', 'magic-string', 'glob', 'svgo'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.index = {}, global.fs, global.path, global.axios, global.lodash, global.prettier, global.compilerSfc, global.magicString, global.glob, global.svgo)); (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.index = {}, global.fs, global.path, global.axios, global.lodashEs, global.prettier, global.compilerSfc, global.magicString, global.glob, global.svgo));
})(this, (function (exports, fs, path, axios, lodash, prettier, compilerSfc, magicString, glob, svgo) { 'use strict'; })(this, (function (exports, fs, path, axios, lodashEs, prettier, compilerSfc, magicString, glob, svgo) { 'use strict';
const config = { const config = {
type: "admin", type: "admin",
@ -141,7 +141,7 @@
// 获取数据 // 获取数据
async function getData(data) { async function getData(data) {
// 自定义数据 // 自定义数据
if (!lodash.isEmpty(data)) { if (!lodashEs.isEmpty(data)) {
customList = (data || []).map((e) => { customList = (data || []).map((e) => {
return { return {
...e, ...e,
@ -149,14 +149,8 @@
}; };
}); });
} }
// 本地文件 // 读取本地数据
const epsPath = getEpsPath("eps.json"); list = readFile(getEpsPath("eps.json"), true) || [];
try {
list = readFile(epsPath, true) || [];
}
catch (err) {
error(`[cool-eps] ${epsPath} 文件异常, ${err.message}`);
}
// 请求地址 // 请求地址
const url = config.reqUrl + getEpsUrl(); const url = config.reqUrl + getEpsUrl();
// 请求数据 // 请求数据
@ -167,23 +161,23 @@
.then((res) => { .then((res) => {
const { code, data, message } = res.data; const { code, data, message } = res.data;
if (code === 1000) { if (code === 1000) {
if (!lodash.isEmpty(data) && data) { if (!lodashEs.isEmpty(data) && data) {
list = lodash.values(data).flat(); list = lodashEs.values(data).flat();
} }
} }
else { else {
error(`[cool-eps] ${message}`); error(`[cool-eps] ${message || "获取数据失败"}`);
} }
}) })
.catch(() => { .catch(() => {
error(`[cool-eps] 后端未启动 ➜ ${url}`); error(`[cool-eps] 后端未启动 ➜ ${url}`);
}); });
// 合并自定义数据 // 合并自定义数据
if (lodash.isArray(customList)) { if (lodashEs.isArray(customList)) {
customList.forEach((e) => { customList.forEach((e) => {
const d = list.find((a) => e.prefix === a.prefix); const d = list.find((a) => e.prefix === a.prefix);
if (d) { if (d) {
lodash.merge(d, e); lodashEs.merge(d, e);
} }
else { else {
list.push(e); list.push(e);
@ -246,79 +240,65 @@
} }
return type; return type;
} }
// 格式化方法名
function formatName(name) {
return (name || "").replace(/[:,\s,\/,-]/g, "");
}
// 创建 Entity // 创建 Entity
function createEntity() { function createEntity() {
const t0 = []; const ignore = [];
const arr = []; let t0 = "";
for (const item of list) { for (const item of list) {
if (!item.name) if (!item.name)
continue; continue;
const t = [`interface ${item.name} {`]; let t = `interface ${formatName(item.name)} {`;
for (const col of item.columns || []) { for (const col of item.columns || []) {
// 描述 t += `
t.push("\n"); /**
t.push("/**\n"); * ${col.comment}
t.push(` * ${col.comment}\n`); */
t.push(" */\n"); ${col.propertyName}?: ${getType({
t.push(`${col.propertyName}?: ${getType({
propertyName: col.propertyName, propertyName: col.propertyName,
type: col.type, type: col.type,
})};`); })}
`;
} }
t.push("\n"); t += `
t.push("/**\n"); /**
t.push(` * 任意键值\n`); * 任意键值
t.push(" */\n"); */
t.push(`[key: string]: any;`); [key: string]: any;
t.push("}"); }
if (!arr.includes(item.name)) { `;
arr.push(item.name); if (!ignore.includes(item.name)) {
t0.push(t); ignore.push(item.name);
t0 += t;
} }
} }
return t0.map((e) => e.join("")).join("\n\n"); return t0;
} }
// 创建 Service // 创建 Service
function createDts() { function createDts() {
const t0 = []; let controller = "";
const t1 = [ let chain = "";
`
type json = any;
type Service = {
request(options?: {
url: string;
method?: "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
data?: any;
params?: any;
headers?: {
[key: string]: any;
},
timeout?: number;
proxy?: boolean;
[key: string]: any;
}): Promise<any>;
`,
];
// 处理数据 // 处理数据
function deep(d, k) { function deep(d, k) {
if (!k) if (!k)
k = ""; k = "";
for (const i in d) { for (const i in d) {
const name = k + toCamel(firstUpperCase(i.replace(/[:]/g, ""))); const name = k + toCamel(firstUpperCase(formatName(i)));
if (d[i].namespace) { if (d[i].namespace) {
// 查找配置 // 查找配置
const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`); const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`);
if (item) { if (item) {
const t = [`interface ${name} {`]; let t = `interface ${name} {`;
t1.push(`${i}: ${name};`);
// 插入方法 // 插入方法
if (item.api) { if (item.api) {
// 权限列表 // 权限列表
const permission = []; const permission = [];
item.api.forEach((a) => { item.api.forEach((a) => {
// 方法名 // 方法名
const n = toCamel(a.name || lodash.last(a.path.split("/")) || "").replace(/[:\/-]/g, ""); const n = toCamel(formatName(a.name || lodashEs.last(a.path.split("/")) || ""));
if (n) { if (n) {
// 参数类型 // 参数类型
let q = []; let q = [];
@ -335,7 +315,7 @@
const b = `${p.schema.type || "string"}`; const b = `${p.schema.type || "string"}`;
q.push(`${a}: ${b},`); q.push(`${a}: ${b},`);
}); });
if (lodash.isEmpty(q)) { if (lodashEs.isEmpty(q)) {
q = ["any"]; q = ["any"];
} }
else { else {
@ -367,57 +347,75 @@
break; break;
} }
// 描述 // 描述
t.push("\n"); t += `
t.push("/**\n"); /**
t.push(` * ${a.summary || n}\n`); * ${a.summary || n}
t.push(" */\n"); */
t.push(`${n}(data${q.length == 1 ? "?" : ""}: ${q.join("")}): Promise<${res}>;`); ${n}(data${q.length == 1 ? "?" : ""}: ${q.join("")}): Promise<${res}>;
`;
if (!permission.includes(n)) { if (!permission.includes(n)) {
permission.push(n); permission.push(n);
} }
} }
}); });
// 权限标识 // 权限标识
t.push("\n"); t += `
t.push("/**\n"); /**
t.push(" * 权限标识\n"); * 权限标识
t.push(" */\n"); */
t.push(`permission: { ${permission permission: { ${permission.map((e) => `${e}: string;`).join("\n")} };
.map((e) => `${e}: string;`) `;
.join("\n")} };`);
// 权限状态 // 权限状态
t.push("\n"); t += `
t.push("/**\n"); /**
t.push(" * 权限状态\n"); * 权限状态
t.push(" */\n"); */
t.push(`_permission: { ${permission _permission: { ${permission.map((e) => `${e}: boolean;`).join("\n")} };
.map((e) => `${e}: boolean;`) `;
.join("\n")} };`); t += `
// 请求 request: Service['request']
t.push("\n"); `;
t.push("/**\n");
t.push(" * 请求\n");
t.push(" */\n");
t.push(`request: Service['request']`);
} }
t.push("}"); t += "}\n\n";
t0.push(t); controller += t;
chain += `${formatName(i)}: ${name};`;
} }
} }
else { else {
t1.push(`${i}: {`); chain += `${formatName(i)}: {`;
deep(d[i], name); deep(d[i], name);
t1.push(`},`); chain += "},";
} }
} }
} }
// 深度 // 遍历
deep(service); deep(service);
// 结束 return `
t1.push("}"); type json = any;
// 追加
t0.push(t1); ${controller}
return t0.map((e) => e.join("")).join("\n\n");
type Service = {
/**
* 基础请求
*/
request(options?: {
url: string;
method?: "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
data?: any;
params?: any;
headers?: {
authorization?: string;
[key: string]: any;
},
timeout?: number;
proxy?: boolean;
[key: string]: any;
}): Promise<any>;
${chain}
}
`;
} }
// 文件内容 // 文件内容
const text = ` const text = `
@ -661,7 +659,7 @@
// 页面配置 // 页面配置
ctx = readFile(ctxPath, true); ctx = readFile(ctxPath, true);
// 原数据,做更新比较用 // 原数据,做更新比较用
const ctxData = lodash.cloneDeep(ctx); const ctxData = lodashEs.cloneDeep(ctx);
// 删除临时页面 // 删除临时页面
ctx.pages = ctx.pages?.filter((e) => !e.isTemp); ctx.pages = ctx.pages?.filter((e) => !e.isTemp);
ctx.subPackages = ctx.subPackages?.filter((e) => !e.isTemp); ctx.subPackages = ctx.subPackages?.filter((e) => !e.isTemp);
@ -681,7 +679,7 @@
? ctx.subPackages?.find((a) => a.root == e.root) ? ctx.subPackages?.find((a) => a.root == e.root)
: ctx.pages?.find((a) => a.path == e.path); : ctx.pages?.find((a) => a.path == e.path);
if (d) { if (d) {
lodash.assign(d, e); lodashEs.assign(d, e);
} }
else { else {
if (isSub) { if (isSub) {
@ -697,12 +695,12 @@
// 排序后检测,避免加载顺序问题 // 排序后检测,避免加载顺序问题
function order(d) { function order(d) {
return { return {
pages: lodash.orderBy(d.pages, "path"), pages: lodashEs.orderBy(d.pages, "path"),
subPackages: lodash.orderBy(d.subPackages, "root"), subPackages: lodashEs.orderBy(d.subPackages, "root"),
}; };
} }
// 是否需要更新 pages.json // 是否需要更新 pages.json
if (!lodash.isEqual(order(ctxData), order(ctx))) { if (!lodashEs.isEqual(order(ctxData), order(ctx))) {
console.log("[cool-ctx] pages updated"); console.log("[cool-ctx] pages updated");
writeFile(ctxPath, JSON.stringify(ctx, null, 4)); writeFile(ctxPath, JSON.stringify(ctx, null, 4));
} }
@ -894,7 +892,7 @@ if (typeof window !== 'undefined') {
} }
// 匹配规则 // 匹配规则
if (mapping) { if (mapping) {
lodash.merge(config.eps.mapping, mapping); lodashEs.merge(config.eps.mapping, mapping);
} }
} }
return [base(), virtual(), demo(options.demo)]; return [base(), virtual(), demo(options.demo)];

View File

@ -1,6 +1,6 @@
{ {
"name": "@cool-vue/vite-plugin", "name": "@cool-vue/vite-plugin",
"version": "7.2.2", "version": "7.2.3",
"description": "cool-admin、cool-uni builder", "description": "cool-admin、cool-uni builder",
"main": "/dist/index.js", "main": "/dist/index.js",
"scripts": { "scripts": {
@ -33,6 +33,7 @@
"axios": "^1.6.8", "axios": "^1.6.8",
"glob": "^10.3.12", "glob": "^10.3.12",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"lodash-es": "^4.17.21",
"magic-string": "^0.30.10", "magic-string": "^0.30.10",
"prettier": "^3.2.5", "prettier": "^3.2.5",
"svgo": "^3.3.2" "svgo": "^3.3.2"

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
import { join } from "path"; import { join } from "path";
import { readFile, rootDir, writeFile, error } from "../utils"; import { readFile, rootDir, writeFile, error } from "../utils";
import { glob } from "glob"; import { glob } from "glob";
import { assign, cloneDeep, isEqual, orderBy } from "lodash"; import { assign, cloneDeep, isEqual, orderBy } from "lodash-es";
import { config } from "../config"; import { config } from "../config";
import fs from "fs"; import fs from "fs";
import axios from "axios"; import axios from "axios";

View File

@ -1,7 +1,7 @@
import { createDir, error, firstUpperCase, readFile, rootDir, toCamel } from "../utils"; import { createDir, error, firstUpperCase, readFile, rootDir, toCamel } from "../utils";
import { join } from "path"; import { join } from "path";
import axios from "axios"; import axios from "axios";
import { isArray, isEmpty, last, merge, values } from "lodash"; import { isArray, isEmpty, last, merge, values } from "lodash-es";
import { createWriteStream } from "fs"; import { createWriteStream } from "fs";
import prettier from "prettier"; import prettier from "prettier";
import { config } from "../config"; import { config } from "../config";
@ -57,14 +57,8 @@ async function getData(data?: Eps.Entity[]) {
}); });
} }
// 本地文件 // 读取本地数据
const epsPath = getEpsPath("eps.json"); list = readFile(getEpsPath("eps.json"), true) || [];
try {
list = readFile(epsPath, true) || [];
} catch (err: any) {
error(`[cool-eps] ${epsPath} 文件异常, ${err.message}`);
}
// 请求地址 // 请求地址
const url = config.reqUrl + getEpsUrl(); const url = config.reqUrl + getEpsUrl();
@ -82,11 +76,11 @@ async function getData(data?: Eps.Entity[]) {
list = values(data).flat(); list = values(data).flat();
} }
} else { } else {
error(`[cool-eps] ${message}`); error(`[cool-eps] ${message || "获取数据失败"}`);
} }
}) })
.catch(() => { .catch(() => {
error(`[cool-eps] 后端未启动 ➜ ${url}`); error(`[cool-eps] 后端未启动 ➜ ${url}`);
}); });
// 合并自定义数据 // 合并自定义数据
@ -163,82 +157,69 @@ async function createDescribe({ list, service }: { list: Eps.Entity[]; service:
return type; return type;
} }
// 格式化方法名
function formatName(name: string) {
return (name || "").replace(/[:,\s,\/,-]/g, "");
}
// 创建 Entity // 创建 Entity
function createEntity() { function createEntity() {
const t0: string[][] = []; const ignore: string[] = [];
const arr: string[] = [];
let t0 = "";
for (const item of list) { for (const item of list) {
if (!item.name) continue; if (!item.name) continue;
const t = [`interface ${item.name} {`];
let t = `interface ${formatName(item.name)} {`;
for (const col of item.columns || []) { for (const col of item.columns || []) {
// 描述 t += `
t.push("\n"); /**
t.push("/**\n"); * ${col.comment}
t.push(` * ${col.comment}\n`); */
t.push(" */\n"); ${col.propertyName}?: ${getType({
t.push(
`${col.propertyName}?: ${getType({
propertyName: col.propertyName, propertyName: col.propertyName,
type: col.type, type: col.type,
})};`, })}
); `;
} }
t.push("\n");
t.push("/**\n");
t.push(` * 任意键值\n`);
t.push(" */\n");
t.push(`[key: string]: any;`);
t.push("}");
if (!arr.includes(item.name)) { t += `
arr.push(item.name); /**
t0.push(t); *
*/
[key: string]: any;
}
`;
if (!ignore.includes(item.name)) {
ignore.push(item.name);
t0 += t;
} }
} }
return t0.map((e) => e.join("")).join("\n\n"); return t0;
} }
// 创建 Service // 创建 Service
function createDts() { function createDts() {
const t0: string[][] = []; let controller = "";
let chain = "";
const t1 = [
`
type json = any;
type Service = {
request(options?: {
url: string;
method?: "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
data?: any;
params?: any;
headers?: {
[key: string]: any;
},
timeout?: number;
proxy?: boolean;
[key: string]: any;
}): Promise<any>;
`,
];
// 处理数据 // 处理数据
function deep(d: any, k?: string) { function deep(d: any, k?: string) {
if (!k) k = ""; if (!k) k = "";
for (const i in d) { for (const i in d) {
const name = k + toCamel(firstUpperCase(i.replace(/[:]/g, ""))); const name = k + toCamel(firstUpperCase(formatName(i)));
if (d[i].namespace) { if (d[i].namespace) {
// 查找配置 // 查找配置
const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`); const item = list.find((e) => (e.prefix || "") === `/${d[i].namespace}`);
if (item) { if (item) {
const t = [`interface ${name} {`]; let t = `interface ${name} {`;
t1.push(`${i}: ${name};`);
// 插入方法 // 插入方法
if (item.api) { if (item.api) {
@ -247,9 +228,8 @@ async function createDescribe({ list, service }: { list: Eps.Entity[]; service:
item.api.forEach((a) => { item.api.forEach((a) => {
// 方法名 // 方法名
const n = toCamel(a.name || last(a.path.split("/")) || "").replace( const n = toCamel(
/[:\/-]/g, formatName(a.name || last(a.path.split("/")) || ""),
"",
); );
if (n) { if (n) {
@ -312,16 +292,12 @@ async function createDescribe({ list, service }: { list: Eps.Entity[]; service:
} }
// 描述 // 描述
t.push("\n"); t += `
t.push("/**\n"); /**
t.push(` * ${a.summary || n}\n`); * ${a.summary || n}
t.push(" */\n"); */
${n}(data${q.length == 1 ? "?" : ""}: ${q.join("")}): Promise<${res}>;
t.push( `;
`${n}(data${q.length == 1 ? "?" : ""}: ${q.join(
"",
)}): Promise<${res}>;`,
);
if (!permission.includes(n)) { if (!permission.includes(n)) {
permission.push(n); permission.push(n);
@ -330,56 +306,68 @@ async function createDescribe({ list, service }: { list: Eps.Entity[]; service:
}); });
// 权限标识 // 权限标识
t.push("\n"); t += `
t.push("/**\n"); /**
t.push(" * 权限标识\n"); *
t.push(" */\n"); */
t.push( permission: { ${permission.map((e) => `${e}: string;`).join("\n")} };
`permission: { ${permission `;
.map((e) => `${e}: string;`)
.join("\n")} };`,
);
// 权限状态 // 权限状态
t.push("\n"); t += `
t.push("/**\n"); /**
t.push(" * 权限状态\n"); *
t.push(" */\n"); */
t.push( _permission: { ${permission.map((e) => `${e}: boolean;`).join("\n")} };
`_permission: { ${permission `;
.map((e) => `${e}: boolean;`)
.join("\n")} };`,
);
// 请求 t += `
t.push("\n"); request: Service['request']
t.push("/**\n"); `;
t.push(" * 请求\n");
t.push(" */\n");
t.push(`request: Service['request']`);
} }
t.push("}"); t += "}\n\n";
t0.push(t);
controller += t;
chain += `${formatName(i)}: ${name};`;
} }
} else { } else {
t1.push(`${i}: {`); chain += `${formatName(i)}: {`;
deep(d[i], name); deep(d[i], name);
t1.push(`},`); chain += "},";
} }
} }
} }
// 深度 // 遍历
deep(service); deep(service);
// 结束 return `
t1.push("}"); type json = any;
// 追加 ${controller}
t0.push(t1);
return t0.map((e) => e.join("")).join("\n\n"); type Service = {
/**
*
*/
request(options?: {
url: string;
method?: "POST" | "GET" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
data?: any;
params?: any;
headers?: {
authorization?: string;
[key: string]: any;
},
timeout?: number;
proxy?: boolean;
[key: string]: any;
}): Promise<any>;
${chain}
}
`;
} }
// 文件内容 // 文件内容

View File

@ -3,7 +3,7 @@ import { config } from "./config";
import { demo } from "./demo"; import { demo } from "./demo";
import { virtual } from "./virtual"; import { virtual } from "./virtual";
import type { Config } from "../types"; import type { Config } from "../types";
import { merge } from "lodash"; import { merge } from "lodash-es";
export function cool(options: Config.Options) { export function cool(options: Config.Options) {
// 应用类型admin | app // 应用类型admin | app