feat 数据库版本,并且增加状态码

This commit is contained in:
2026-04-23 18:50:03 +08:00
parent 7ae07a6fcb
commit f44f0c2cea
8 changed files with 1524 additions and 46 deletions
+309 -42
View File
@@ -3,17 +3,25 @@ import * as https from "https";
import * as fs from "fs";
import * as path from "path";
import * as zlib from "zlib";
import sqlite3 from "sqlite3";
// 配置文件路径
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");
const DATA_DIR = path.join(__dirname, "data");
const DB_FILE = path.join(DATA_DIR, "mock-mappings.sqlite3");
const LEGACY_DB_FILE = path.join(MOCK_DIR, "mock-mappings.sqlite3");
// 定义类型
interface RouteConfig {
[route: string]: string;
}
interface RouteStatusConfig {
[route: string]: number;
}
interface AppConfig {
/** 为 false 时所有请求走代理,不命中 mock 路由;缺省为 true */
mockEnabled?: boolean;
@@ -30,6 +38,7 @@ interface AppConfig {
interface ConfigFile {
routes: RouteConfig;
routeStatuses?: RouteStatusConfig;
config: AppConfig;
}
@@ -43,9 +52,21 @@ interface MockFileItem {
content: string;
}
interface RouteRow {
route_key: string;
file_path: string;
status_code: number;
}
interface MockFileRow {
file_path: string;
}
// 存储当前的路由配置
let MOCK_ROUTES: RouteConfig = {};
let RAW_ROUTES: RouteConfig = {};
let MOCK_ROUTE_STATUSES: RouteStatusConfig = {};
let RAW_ROUTE_STATUSES: RouteStatusConfig = {};
let CONFIG: AppConfig = {
cacheConfig: true,
reloadOnChange: true,
@@ -54,6 +75,7 @@ let CONFIG: AppConfig = {
targetHost: "localhost",
targetPort: 443,
};
let DB: sqlite3.Database;
// 过滤掉以 # 开头的路由(视为注释,不参与 mock)
function filterActiveRoutes(routes: RouteConfig): RouteConfig {
@@ -65,6 +87,24 @@ function filterActiveRoutes(routes: RouteConfig): RouteConfig {
return filtered;
}
function filterActiveRouteStatuses(statuses: RouteStatusConfig): RouteStatusConfig {
const filtered: RouteStatusConfig = {};
for (const [route, statusCode] of Object.entries(statuses)) {
if (route.startsWith("#")) continue;
filtered[route] = statusCode;
}
return filtered;
}
function normalizeStatusCode(input: unknown, fallback = 200): number {
const numeric =
typeof input === "number" ? input : Number.parseInt(String(input ?? ""), 10);
if (Number.isInteger(numeric) && numeric >= 100 && numeric <= 599) {
return numeric;
}
return fallback;
}
function isTargetHttps(): boolean {
return CONFIG.targetHttps !== false;
}
@@ -83,8 +123,146 @@ function upstreamRequest(
: http.request(options, callback);
}
function dbRun(sql: string, params: unknown[] = []): Promise<void> {
return new Promise((resolve, reject) => {
DB.run(sql, params, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
function dbAll<T = unknown>(sql: string, params: unknown[] = []): Promise<T[]> {
return new Promise((resolve, reject) => {
DB.all(sql, params, (error, rows) => {
if (error) {
reject(error);
return;
}
resolve((rows as T[]) || []);
});
});
}
function openDatabase(): Promise<void> {
return new Promise((resolve, reject) => {
DB = new sqlite3.Database(DB_FILE, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
async function initDatabase(): Promise<void> {
fs.mkdirSync(MOCK_DIR, { recursive: true });
fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(DB_FILE) && fs.existsSync(LEGACY_DB_FILE)) {
fs.copyFileSync(LEGACY_DB_FILE, DB_FILE);
}
await openDatabase();
await dbRun(`
CREATE TABLE IF NOT EXISTS route_mappings (
route_key TEXT PRIMARY KEY,
file_path TEXT NOT NULL,
status_code INTEGER NOT NULL DEFAULT 200
)
`);
await dbRun(
"ALTER TABLE route_mappings ADD COLUMN status_code INTEGER NOT NULL DEFAULT 200",
).catch(() => {
// ignore when column already exists
});
await dbRun(`
CREATE TABLE IF NOT EXISTS api_list (
route TEXT PRIMARY KEY,
name TEXT NOT NULL
)
`);
await dbRun(`
CREATE TABLE IF NOT EXISTS mock_files (
file_path TEXT PRIMARY KEY
)
`);
// 清理不该出现在 mock 列表中的系统文件
await dbRun(
"DELETE FROM mock_files WHERE file_path = ? OR file_path LIKE ?",
["mock/api-list.json", "%.sqlite3"],
);
}
async function saveRoutesToDb(
routes: RouteConfig,
routeStatuses: RouteStatusConfig = {},
): Promise<void> {
await dbRun("DELETE FROM route_mappings");
for (const [routeKey, filePath] of Object.entries(routes)) {
const statusCode = normalizeStatusCode(routeStatuses[routeKey], 200);
await dbRun(
"INSERT INTO route_mappings(route_key, file_path, status_code) VALUES(?, ?, ?)",
[routeKey, filePath, statusCode],
);
await dbRun("INSERT OR IGNORE INTO mock_files(file_path) VALUES(?)", [
filePath,
]);
}
}
async function loadRoutesFromDb(): Promise<{
routes: RouteConfig;
routeStatuses: RouteStatusConfig;
}> {
const rows = await dbAll<RouteRow>(
"SELECT route_key, file_path, status_code FROM route_mappings ORDER BY route_key ASC",
);
const routes: RouteConfig = {};
const routeStatuses: RouteStatusConfig = {};
for (const row of rows) {
routes[row.route_key] = row.file_path;
routeStatuses[row.route_key] = normalizeStatusCode(row.status_code, 200);
}
return { routes, routeStatuses };
}
async function upsertApiListToDb(list: ApiListItem[]): Promise<void> {
await dbRun("DELETE FROM api_list");
for (const item of list) {
await dbRun("INSERT INTO api_list(route, name) VALUES(?, ?)", [
item.route,
item.name,
]);
}
}
async function loadApiListFromDb(): Promise<ApiListItem[]> {
const rows = await dbAll<{ route: string; name: string }>(
"SELECT route, name FROM api_list ORDER BY route ASC",
);
return rows.map((row) => ({ route: row.route, name: row.name }));
}
async function upsertMockFilePathToDb(filePath: string): Promise<void> {
await dbRun("INSERT OR IGNORE INTO mock_files(file_path) VALUES(?)", [filePath]);
}
async function removeMockFilePathFromDb(filePath: string): Promise<void> {
await dbRun("DELETE FROM mock_files WHERE file_path = ?", [filePath]);
}
async function loadMockFilePathsFromDb(): Promise<string[]> {
const rows = await dbAll<MockFileRow>(
"SELECT file_path FROM mock_files ORDER BY file_path ASC",
);
return rows.map((row) => row.file_path);
}
// 加载配置文件
function loadConfig() {
async function loadConfig() {
try {
if (!fs.existsSync(CONFIG_FILE)) {
console.warn(`[CONFIG] 配置文件不存在: ${CONFIG_FILE}`);
@@ -119,25 +297,32 @@ function loadConfig() {
);
console.log(`[CONFIG] 已创建默认配置文件: ${CONFIG_FILE}`);
// 加载配置(# 开头的路由视为注释,不参与 mock)
// 加载配置,路由最终以 sqlite 为准
const configData: ConfigFile = JSON.parse(
fs.readFileSync(CONFIG_FILE, "utf-8"),
);
RAW_ROUTES = configData.routes || {};
MOCK_ROUTES = filterActiveRoutes(RAW_ROUTES);
CONFIG = configData.config || CONFIG;
await saveRoutesToDb(configData.routes || {}, configData.routeStatuses || {});
} else {
const configData: ConfigFile = JSON.parse(
fs.readFileSync(CONFIG_FILE, "utf-8"),
);
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 已关闭,全部走代理)"}`,
);
const dbMappings = await loadRoutesFromDb();
if (Object.keys(dbMappings.routes).length === 0 && configData.routes) {
await saveRoutesToDb(configData.routes, configData.routeStatuses || {});
}
}
const dbMappings = await loadRoutesFromDb();
RAW_ROUTES = dbMappings.routes;
RAW_ROUTE_STATUSES = dbMappings.routeStatuses;
MOCK_ROUTES = filterActiveRoutes(RAW_ROUTES);
MOCK_ROUTE_STATUSES = filterActiveRouteStatuses(RAW_ROUTE_STATUSES);
console.log(
`[CONFIG] 配置已加载(sqlite 路由 ${Object.keys(MOCK_ROUTES).length} 条)${CONFIG.mockEnabled !== false ? "" : "(mock 已关闭,全部走代理)"}`,
);
// 验证mock文件是否存在
validateMockFiles();
} catch (error) {
@@ -147,6 +332,8 @@ function loadConfig() {
"/api2/user/list": "mock/user_list.txt",
};
RAW_ROUTES = { ...MOCK_ROUTES };
RAW_ROUTE_STATUSES = {};
MOCK_ROUTE_STATUSES = {};
CONFIG = {
cacheConfig: true,
reloadOnChange: true,
@@ -161,18 +348,24 @@ function loadConfig() {
function buildCurrentConfigFile(): ConfigFile {
return {
routes: { ...RAW_ROUTES },
routeStatuses: { ...RAW_ROUTE_STATUSES },
config: { ...CONFIG },
};
}
function saveConfigFile(nextConfig: ConfigFile): void {
async function saveConfigFile(nextConfig: ConfigFile): Promise<void> {
// routes 持久化到 sqlite,config 仍使用 config.json
await saveRoutesToDb(nextConfig.routes || {}, nextConfig.routeStatuses || {});
fs.writeFileSync(CONFIG_FILE, JSON.stringify(nextConfig, null, 2), "utf-8");
RAW_ROUTES = nextConfig.routes || {};
const dbMappings = await loadRoutesFromDb();
RAW_ROUTES = dbMappings.routes;
RAW_ROUTE_STATUSES = dbMappings.routeStatuses;
MOCK_ROUTES = filterActiveRoutes(RAW_ROUTES);
MOCK_ROUTE_STATUSES = filterActiveRouteStatuses(RAW_ROUTE_STATUSES);
CONFIG = nextConfig.config || CONFIG;
}
function loadApiList(): ApiListItem[] {
function loadApiListFromJson(): ApiListItem[] {
if (!fs.existsSync(API_LIST_FILE)) {
return [];
}
@@ -203,6 +396,18 @@ function loadApiList(): ApiListItem[] {
}
}
async function loadApiList(): Promise<ApiListItem[]> {
const dbList = await loadApiListFromDb();
if (dbList.length > 0) {
return dbList;
}
const jsonList = loadApiListFromJson();
if (jsonList.length > 0) {
await upsertApiListToDb(jsonList);
}
return jsonList;
}
function normalizeMockFilePath(filePath: string): string {
const trimmed = filePath.trim().replace(/\\/g, "/");
if (!trimmed) {
@@ -238,25 +443,52 @@ function walkMockFiles(dir: string, baseDir: string, result: string[]): void {
}
if (!entry.isFile()) continue;
if (entry.name === "api-list.json") continue;
if (entry.name.endsWith(".sqlite3")) continue;
const relative = path.relative(baseDir, fullPath).replace(/\\/g, "/");
result.push(`mock/${relative}`);
}
}
function loadMockFiles(): MockFileItem[] {
async function loadMockFiles(): Promise<MockFileItem[]> {
let files = await loadMockFilePathsFromDb();
files = files.filter(
(filePath) =>
filePath !== "mock/api-list.json" && !filePath.endsWith(".sqlite3"),
);
if (files.length === 0 && fs.existsSync(MOCK_DIR)) {
const fsFiles: string[] = [];
walkMockFiles(MOCK_DIR, MOCK_DIR, fsFiles);
fsFiles.sort((a, b) => a.localeCompare(b));
for (const filePath of fsFiles) {
await upsertMockFilePathToDb(filePath);
}
files = fsFiles;
}
const result: MockFileItem[] = [];
for (const filePath of files) {
const fullPath = path.join(__dirname, filePath);
if (!fs.existsSync(fullPath)) continue;
result.push({
filePath,
content: fs.readFileSync(fullPath, "utf-8"),
});
}
return result;
}
async function initMockFilesFromFsIfNeeded(): Promise<void> {
const filesInDb = await loadMockFilePathsFromDb();
if (filesInDb.length > 0 || !fs.existsSync(MOCK_DIR)) return;
if (!fs.existsSync(MOCK_DIR)) {
return [];
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"),
};
});
for (const filePath of files) {
await upsertMockFilePathToDb(filePath);
}
}
function readBody(req: http.IncomingMessage): Promise<string> {
@@ -309,6 +541,10 @@ function getMockFilePath(requestPath: string): string {
return MOCK_ROUTES[requestPath];
}
function getMockStatusCode(requestPath: string): number {
return normalizeStatusCode(MOCK_ROUTE_STATUSES[requestPath], 200);
}
function decodeBodyByEncoding(
bodyBuffer: Buffer,
contentEncoding?: string,
@@ -331,7 +567,7 @@ function decodeBodyByEncoding(
}
// 代理服务器
const proxyServer = http.createServer((clientReq, clientRes) => {
const proxyServer = http.createServer(async (clientReq, clientRes) => {
// 解析客户端请求的 URL
const parsedUrl = new URL(`http://localhost${clientReq.url!}`);
const requestPath = parsedUrl.pathname;
@@ -355,7 +591,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
try {
const oldCount = Object.keys(MOCK_ROUTES).length;
loadConfig();
await loadConfig();
const newCount = Object.keys(MOCK_ROUTES).length;
clientRes.writeHead(200, { "Content-Type": "application/json" });
@@ -400,13 +636,14 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
if (clientReq.method === "POST") {
readBody(clientReq)
.then((bodyText) => {
.then(async (bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {};
const nextConfig: ConfigFile = {
routes: body.routes || {},
routes: body.routes ?? RAW_ROUTES,
routeStatuses: body.routeStatuses ?? RAW_ROUTE_STATUSES,
config: body.config || CONFIG,
};
saveConfigFile(nextConfig);
await saveConfigFile(nextConfig);
validateMockFiles();
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
@@ -435,6 +672,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
JSON.stringify(
{
routes: RAW_ROUTES,
routeStatuses: RAW_ROUTE_STATUSES,
config: CONFIG,
timestamp: new Date().toISOString(),
totalRoutes: Object.keys(MOCK_ROUTES).length,
@@ -472,7 +710,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
}
readBody(clientReq)
.then((bodyText) => {
.then(async (bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {};
let route = String(body.route || "").trim();
const filePath = String(body.filePath || "").trim();
@@ -483,10 +721,11 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
const selectedApiRoute = String(body.selectedApiRoute || "").trim();
const originalRoute = String(body.originalRoute || "").trim();
const originalRawRoute = String(body.originalRawRoute || "").trim();
const statusCode = normalizeStatusCode(body.statusCode, 200);
const enabled = body.enabled !== false;
const useExistingFile =
body.useExistingFile === true || template === "basicError";
const apiList = loadApiList();
const apiList = await loadApiList();
const selectedApi = selectedApiRoute
? apiList.find((item) => item.route === selectedApiRoute)
: undefined;
@@ -543,10 +782,16 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
oldRouteCandidates.forEach((key) => {
if (key && key !== nextRouteKey) {
delete nextConfig.routes[key];
delete nextConfig.routeStatuses?.[key];
}
});
nextConfig.routes[nextRouteKey] = normalizedFilePath;
saveConfigFile(nextConfig);
if (!nextConfig.routeStatuses) {
nextConfig.routeStatuses = {};
}
nextConfig.routeStatuses[nextRouteKey] = statusCode;
await saveConfigFile(nextConfig);
await upsertMockFilePathToDb(normalizedFilePath);
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
@@ -556,6 +801,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
route,
routeKey: nextRouteKey,
filePath: normalizedFilePath,
statusCode,
enabled,
}),
);
@@ -591,7 +837,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
clientRes.end(
JSON.stringify({
success: true,
list: loadApiList(),
list: await loadApiList(),
}),
);
return;
@@ -622,14 +868,14 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
clientRes.end(
JSON.stringify({
success: true,
list: loadMockFiles(),
list: await loadMockFiles(),
}),
);
return;
}
readBody(clientReq)
.then((bodyText) => {
.then(async (bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {};
const filePath = String(body.filePath || "").trim();
const fullPath = resolveMockFullPath(filePath);
@@ -639,6 +885,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
const content = String(body.content || "");
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content, "utf-8");
await upsertMockFilePathToDb(normalizedPath);
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
@@ -654,6 +901,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
throw new Error("mock file does not exist");
}
fs.unlinkSync(fullPath);
await removeMockFilePathFromDb(normalizedPath);
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
@@ -695,6 +943,7 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
// 检查是否为需要mock的路由
if (isMockRoute(requestPath)) {
const mockFile = getMockFilePath(requestPath);
const mockStatusCode = getMockStatusCode(requestPath);
console.log(`[MOCK] 拦截路由: ${requestPath} -> 使用文件: ${mockFile}`);
try {
@@ -748,10 +997,11 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
console.error(`[MOCK] 自动写入mock文件失败: ${mockFilePath}`, writeErr);
}
clientRes.writeHead(proxyRes.statusCode || 200, {
clientRes.writeHead(mockStatusCode, {
...proxyRes.headers,
"X-Mock-Autogenerated": "true",
"X-Mock-Source": mockFile,
"X-Mock-Status-Code": String(mockStatusCode),
});
clientRes.end(bodyBuffer);
});
@@ -780,12 +1030,13 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
// 设置响应头
const contentType = CONFIG.defaultContentType || "application/json";
clientRes.writeHead(200, {
clientRes.writeHead(mockStatusCode, {
"Content-Type": contentType,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"X-Mock-Source": mockFile,
"X-Mock-Status-Code": String(mockStatusCode),
"X-Mock-Timestamp": new Date().toISOString(),
});
@@ -849,16 +1100,13 @@ const proxyServer = http.createServer((clientReq, clientRes) => {
clientReq.pipe(proxyReq);
});
// 初始化:第一次加载配置
loadConfig();
// 如果配置了文件监视,则监听配置文件变化
if (CONFIG.reloadOnChange) {
fs.watchFile(CONFIG_FILE, (curr, prev) => {
function setupConfigWatcher(): void {
if (!CONFIG.reloadOnChange) return;
fs.watchFile(CONFIG_FILE, async () => {
console.log(`[CONFIG] 配置文件已修改,重新加载...`);
try {
const oldRoutesCount = Object.keys(MOCK_ROUTES).length;
loadConfig();
await loadConfig();
const newRoutesCount = Object.keys(MOCK_ROUTES).length;
console.log(
`[CONFIG] 配置重载完成 (路由数: ${oldRoutesCount} -> ${newRoutesCount})`,
@@ -870,7 +1118,8 @@ if (CONFIG.reloadOnChange) {
console.log(`[CONFIG] 已启用配置文件监视: ${CONFIG_FILE}`);
}
proxyServer.listen(CONFIG.proxyPort, "0.0.0.0", () => {
function startServer(): void {
proxyServer.listen(CONFIG.proxyPort, "0.0.0.0", () => {
const targetPort = getTargetPort();
const proto = isTargetHttps() ? "https" : "http";
const defaultPort = isTargetHttps() ? 443 : 80;
@@ -900,4 +1149,22 @@ proxyServer.listen(CONFIG.proxyPort, "0.0.0.0", () => {
console.log(` ${exists} ${route} -> ${file}`);
}
console.log(`========================================`);
});
}
async function bootstrap(): Promise<void> {
await initDatabase();
await initMockFilesFromFsIfNeeded();
await loadConfig();
const apiListFromDb = await loadApiListFromDb();
if (apiListFromDb.length === 0) {
await upsertApiListToDb(loadApiListFromJson());
}
setupConfigWatcher();
startServer();
}
bootstrap().catch((error) => {
console.error("[BOOTSTRAP] 启动失败:", error);
process.exit(1);
});