feat: 增加mock配置

This commit is contained in:
2026-04-23 18:02:34 +08:00
parent 8d20792fc3
commit 7ae07a6fcb
3 changed files with 804 additions and 134 deletions
+251 -14
View File
@@ -6,6 +6,8 @@ import * as zlib from "zlib";
// 配置文件路径
const CONFIG_FILE = path.join(__dirname, "config.json");
const API_LIST_FILE = path.join(__dirname, "mock", "api-list.json");
const MOCK_DIR = path.join(__dirname, "mock");
// 定义类型
interface RouteConfig {
@@ -31,6 +33,16 @@ interface ConfigFile {
config: AppConfig;
}
interface ApiListItem {
name: string;
route: string;
}
interface MockFileItem {
filePath: string;
content: string;
}
// 存储当前的路由配置
let MOCK_ROUTES: RouteConfig = {};
let RAW_ROUTES: RouteConfig = {};
@@ -160,6 +172,93 @@ function saveConfigFile(nextConfig: ConfigFile): void {
CONFIG = nextConfig.config || CONFIG;
}
function loadApiList(): ApiListItem[] {
if (!fs.existsSync(API_LIST_FILE)) {
return [];
}
try {
const text = fs.readFileSync(API_LIST_FILE, "utf-8").trim();
if (!text) {
return [];
}
const parsed = JSON.parse(text);
if (!Array.isArray(parsed)) {
return [];
}
const seenRoutes = new Set<string>();
const list: ApiListItem[] = [];
for (const item of parsed) {
const route = String(item?.route || "").trim();
const name = String(item?.name || "").trim();
if (!route || !route.startsWith("/") || !name || seenRoutes.has(route)) {
continue;
}
seenRoutes.add(route);
list.push({ name, route });
}
return list;
} catch (error) {
console.warn("[ADMIN] 读取 api-list.json 失败:", error);
return [];
}
}
function normalizeMockFilePath(filePath: string): string {
const trimmed = filePath.trim().replace(/\\/g, "/");
if (!trimmed) {
throw new Error("filePath is required");
}
const relative = trimmed.startsWith("mock/") ? trimmed : `mock/${trimmed}`;
if (path.isAbsolute(relative)) {
throw new Error("filePath must be a relative path");
}
return relative;
}
function resolveMockFullPath(relativePath: string): string {
const normalized = normalizeMockFilePath(relativePath);
const fullPath = path.resolve(__dirname, normalized);
const mockRoot = path.resolve(MOCK_DIR);
if (!fullPath.startsWith(mockRoot)) {
throw new Error("filePath is invalid");
}
if (path.basename(fullPath) === "api-list.json") {
throw new Error("api-list.json is read-only in this panel");
}
return fullPath;
}
function walkMockFiles(dir: string, baseDir: string, result: string[]): void {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkMockFiles(fullPath, baseDir, result);
continue;
}
if (!entry.isFile()) continue;
if (entry.name === "api-list.json") continue;
const relative = path.relative(baseDir, fullPath).replace(/\\/g, "/");
result.push(`mock/${relative}`);
}
}
function loadMockFiles(): MockFileItem[] {
if (!fs.existsSync(MOCK_DIR)) {
return [];
}
const files: string[] = [];
walkMockFiles(MOCK_DIR, MOCK_DIR, files);
files.sort((a, b) => a.localeCompare(b));
return files.map((filePath) => {
const fullPath = path.join(__dirname, filePath);
return {
filePath,
content: fs.readFileSync(fullPath, "utf-8"),
};
});
}
function readBody(req: http.IncomingMessage): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
@@ -375,28 +474,48 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
readBody(clientReq)
.then((bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {};
const route = String(body.route || "").trim();
let route = String(body.route || "").trim();
const filePath = String(body.filePath || "").trim();
const fileContent = String(body.fileContent || "");
const overwrite = body.overwrite === true;
const template = String(body.template || "").trim();
const apiName = String(body.apiName || "").trim();
const selectedApiRoute = String(body.selectedApiRoute || "").trim();
const originalRoute = String(body.originalRoute || "").trim();
const originalRawRoute = String(body.originalRawRoute || "").trim();
const enabled = body.enabled !== false;
const useExistingFile =
body.useExistingFile === true || template === "basicError";
const apiList = loadApiList();
const selectedApi = selectedApiRoute
? apiList.find((item) => item.route === selectedApiRoute)
: undefined;
const originalApi = originalRoute
? apiList.find((item) => item.route === originalRoute)
: undefined;
// 来自 api-list 的接口路由不可在新增/修改时变更
if (selectedApi) {
if (route && route !== selectedApi.route) {
throw new Error("api-list route cannot be changed");
}
if (apiName && apiName !== selectedApi.name) {
throw new Error("api-list name cannot be changed");
}
route = selectedApi.route;
}
if (originalApi && route !== originalApi.route) {
throw new Error("api-list route cannot be changed");
}
if (originalApi && apiName && apiName !== originalApi.name) {
throw new Error("api-list name cannot be changed");
}
if (!route.startsWith("/")) {
throw new Error("route must start with '/'");
}
if (!filePath) {
throw new Error("filePath is required");
}
if (path.isAbsolute(filePath)) {
throw new Error("filePath must be a relative path");
}
const fullPath = path.join(__dirname, filePath);
if (!fullPath.startsWith(__dirname)) {
throw new Error("filePath is invalid");
}
const normalizedFilePath = normalizeMockFilePath(filePath);
const fullPath = resolveMockFullPath(normalizedFilePath);
if (useExistingFile) {
if (!fs.existsSync(fullPath)) {
throw new Error("mock file does not exist");
@@ -412,7 +531,21 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
}
const nextConfig = buildCurrentConfigFile();
nextConfig.routes[route] = filePath;
const nextRouteKey = enabled ? route : `#${route}`;
const oldRouteCandidates = new Set<string>();
if (originalRawRoute) {
oldRouteCandidates.add(originalRawRoute);
}
if (originalRoute) {
oldRouteCandidates.add(originalRoute);
oldRouteCandidates.add(`#${originalRoute}`);
}
oldRouteCandidates.forEach((key) => {
if (key && key !== nextRouteKey) {
delete nextConfig.routes[key];
}
});
nextConfig.routes[nextRouteKey] = normalizedFilePath;
saveConfigFile(nextConfig);
clientRes.writeHead(200, { "Content-Type": "application/json" });
@@ -421,7 +554,111 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
success: true,
message: "Route and mock file created successfully",
route,
filePath,
routeKey: nextRouteKey,
filePath: normalizedFilePath,
enabled,
}),
);
})
.catch((error) => {
clientRes.writeHead(400, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: false,
error: (error as Error).message,
}),
);
});
return;
}
if (requestPath === "/__api-list") {
if (clientReq.method !== "GET") {
clientRes.writeHead(405, {
"Content-Type": "application/json",
Allow: "GET",
});
clientRes.end(
JSON.stringify({
success: false,
error: "Method Not Allowed",
allow: ["GET"],
}),
);
return;
}
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
list: loadApiList(),
}),
);
return;
}
if (requestPath === "/__mock-files") {
if (
clientReq.method !== "GET" &&
clientReq.method !== "POST" &&
clientReq.method !== "DELETE"
) {
clientRes.writeHead(405, {
"Content-Type": "application/json",
Allow: "GET, POST, DELETE",
});
clientRes.end(
JSON.stringify({
success: false,
error: "Method Not Allowed",
allow: ["GET", "POST", "DELETE"],
}),
);
return;
}
if (clientReq.method === "GET") {
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
list: loadMockFiles(),
}),
);
return;
}
readBody(clientReq)
.then((bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {};
const filePath = String(body.filePath || "").trim();
const fullPath = resolveMockFullPath(filePath);
const normalizedPath = normalizeMockFilePath(filePath);
if (clientReq.method === "POST") {
const content = String(body.content || "");
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content, "utf-8");
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
filePath: normalizedPath,
}),
);
return;
}
// DELETE
if (!fs.existsSync(fullPath)) {
throw new Error("mock file does not exist");
}
fs.unlinkSync(fullPath);
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
filePath: normalizedPath,
}),
);
})