feat: 新增web配置中心
This commit is contained in:
+165
-6
@@ -33,6 +33,7 @@ interface ConfigFile {
|
||||
|
||||
// 存储当前的路由配置
|
||||
let MOCK_ROUTES: RouteConfig = {};
|
||||
let RAW_ROUTES: RouteConfig = {};
|
||||
let CONFIG: AppConfig = {
|
||||
cacheConfig: true,
|
||||
reloadOnChange: true,
|
||||
@@ -110,13 +111,15 @@ function loadConfig() {
|
||||
const configData: ConfigFile = JSON.parse(
|
||||
fs.readFileSync(CONFIG_FILE, "utf-8"),
|
||||
);
|
||||
MOCK_ROUTES = filterActiveRoutes(configData.routes || {});
|
||||
RAW_ROUTES = configData.routes || {};
|
||||
MOCK_ROUTES = filterActiveRoutes(RAW_ROUTES);
|
||||
CONFIG = configData.config || CONFIG;
|
||||
} else {
|
||||
const configData: ConfigFile = JSON.parse(
|
||||
fs.readFileSync(CONFIG_FILE, "utf-8"),
|
||||
);
|
||||
MOCK_ROUTES = filterActiveRoutes(configData.routes || {});
|
||||
RAW_ROUTES = configData.routes || {};
|
||||
MOCK_ROUTES = filterActiveRoutes(RAW_ROUTES);
|
||||
CONFIG = configData.config || CONFIG;
|
||||
console.log(
|
||||
`[CONFIG] 配置文件已加载,共 ${Object.keys(MOCK_ROUTES).length} 个路由${CONFIG.mockEnabled !== false ? "" : "(mock 已关闭,全部走代理)"}`,
|
||||
@@ -131,6 +134,7 @@ function loadConfig() {
|
||||
MOCK_ROUTES = {
|
||||
"/api2/user/list": "mock/user_list.txt",
|
||||
};
|
||||
RAW_ROUTES = { ...MOCK_ROUTES };
|
||||
CONFIG = {
|
||||
cacheConfig: true,
|
||||
reloadOnChange: true,
|
||||
@@ -142,6 +146,31 @@ function loadConfig() {
|
||||
}
|
||||
}
|
||||
|
||||
function buildCurrentConfigFile(): ConfigFile {
|
||||
return {
|
||||
routes: { ...RAW_ROUTES },
|
||||
config: { ...CONFIG },
|
||||
};
|
||||
}
|
||||
|
||||
function saveConfigFile(nextConfig: ConfigFile): void {
|
||||
fs.writeFileSync(CONFIG_FILE, JSON.stringify(nextConfig, null, 2), "utf-8");
|
||||
RAW_ROUTES = nextConfig.routes || {};
|
||||
MOCK_ROUTES = filterActiveRoutes(RAW_ROUTES);
|
||||
CONFIG = nextConfig.config || CONFIG;
|
||||
}
|
||||
|
||||
function readBody(req: http.IncomingMessage): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (chunk: Buffer) => {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
});
|
||||
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
// 验证mock文件是否存在
|
||||
function validateMockFiles() {
|
||||
console.log(`[CONFIG] 验证mock文件...`);
|
||||
@@ -255,27 +284,58 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
|
||||
}
|
||||
|
||||
if (requestPath === "/__config") {
|
||||
if (clientReq.method !== "GET") {
|
||||
if (clientReq.method !== "GET" && clientReq.method !== "POST") {
|
||||
clientRes.writeHead(405, {
|
||||
"Content-Type": "application/json",
|
||||
Allow: "GET",
|
||||
Allow: "GET, POST",
|
||||
});
|
||||
clientRes.end(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: "Method Not Allowed",
|
||||
allow: ["GET"],
|
||||
allow: ["GET", "POST"],
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (clientReq.method === "POST") {
|
||||
readBody(clientReq)
|
||||
.then((bodyText) => {
|
||||
const body = bodyText ? JSON.parse(bodyText) : {};
|
||||
const nextConfig: ConfigFile = {
|
||||
routes: body.routes || {},
|
||||
config: body.config || CONFIG,
|
||||
};
|
||||
saveConfigFile(nextConfig);
|
||||
validateMockFiles();
|
||||
clientRes.writeHead(200, { "Content-Type": "application/json" });
|
||||
clientRes.end(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: "Configuration saved successfully",
|
||||
totalRoutes: Object.keys(MOCK_ROUTES).length,
|
||||
}),
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
clientRes.writeHead(400, { "Content-Type": "application/json" });
|
||||
clientRes.end(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: (error as Error).message,
|
||||
}),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
clientRes.writeHead(200, { "Content-Type": "application/json" });
|
||||
clientRes.end(
|
||||
JSON.stringify(
|
||||
{
|
||||
routes: MOCK_ROUTES,
|
||||
routes: RAW_ROUTES,
|
||||
config: CONFIG,
|
||||
timestamp: new Date().toISOString(),
|
||||
totalRoutes: Object.keys(MOCK_ROUTES).length,
|
||||
@@ -296,6 +356,105 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestPath === "/__routes") {
|
||||
if (clientReq.method !== "POST") {
|
||||
clientRes.writeHead(405, {
|
||||
"Content-Type": "application/json",
|
||||
Allow: "POST",
|
||||
});
|
||||
clientRes.end(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: "Method Not Allowed",
|
||||
allow: ["POST"],
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
readBody(clientReq)
|
||||
.then((bodyText) => {
|
||||
const body = bodyText ? JSON.parse(bodyText) : {};
|
||||
const 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 useExistingFile =
|
||||
body.useExistingFile === true || template === "basicError";
|
||||
|
||||
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");
|
||||
}
|
||||
if (useExistingFile) {
|
||||
if (!fs.existsSync(fullPath)) {
|
||||
throw new Error("mock file does not exist");
|
||||
}
|
||||
} else {
|
||||
if (!overwrite && fs.existsSync(fullPath)) {
|
||||
throw new Error(
|
||||
"mock file already exists, set overwrite=true to replace",
|
||||
);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
fs.writeFileSync(fullPath, fileContent, "utf-8");
|
||||
}
|
||||
|
||||
const nextConfig = buildCurrentConfigFile();
|
||||
nextConfig.routes[route] = filePath;
|
||||
saveConfigFile(nextConfig);
|
||||
|
||||
clientRes.writeHead(200, { "Content-Type": "application/json" });
|
||||
clientRes.end(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: "Route and mock file created successfully",
|
||||
route,
|
||||
filePath,
|
||||
}),
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
clientRes.writeHead(400, { "Content-Type": "application/json" });
|
||||
clientRes.end(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: (error as Error).message,
|
||||
}),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestPath === "/__admin") {
|
||||
if (clientReq.method !== "GET") {
|
||||
clientRes.writeHead(405, { "Content-Type": "text/plain; charset=utf-8" });
|
||||
clientRes.end("Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
const adminHtmlPath = path.join(__dirname, "admin.html");
|
||||
if (!fs.existsSync(adminHtmlPath)) {
|
||||
clientRes.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
||||
clientRes.end("admin.html not found");
|
||||
return;
|
||||
}
|
||||
const html = fs.readFileSync(adminHtmlPath, "utf-8");
|
||||
clientRes.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
||||
clientRes.end(html);
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否为需要mock的路由
|
||||
if (isMockRoute(requestPath)) {
|
||||
const mockFile = getMockFilePath(requestPath);
|
||||
|
||||
Reference in New Issue
Block a user