重构数据库版本
This commit is contained in:
@@ -0,0 +1,293 @@
|
||||
import * as fs from "fs";
|
||||
import sqlite3 from "sqlite3";
|
||||
import { DB_FILE, LEGACY_DB_FILE, MOCK_DIR, DATA_DIR } from "./constants";
|
||||
import { state } from "./state";
|
||||
import { normalizeStatusCode } from "./utils";
|
||||
import type {
|
||||
ApiListItem,
|
||||
AppConfig,
|
||||
MockFileRow,
|
||||
RouteApiNameMap,
|
||||
RouteConfig,
|
||||
RouteEnabledMap,
|
||||
RouteRow,
|
||||
RouteStatusConfig,
|
||||
} from "./types";
|
||||
|
||||
export function dbRun(sql: string, params: unknown[] = []): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
state.db.run(sql, params, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function dbAll<T = unknown>(
|
||||
sql: string,
|
||||
params: unknown[] = [],
|
||||
): Promise<T[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
state.db.all(sql, params, (error, rows) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve((rows as T[]) || []);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function openDatabase(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
state.db = new sqlite3.Database(DB_FILE, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export 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(
|
||||
"ALTER TABLE route_mappings ADD COLUMN enabled INTEGER NOT NULL DEFAULT 1",
|
||||
).catch(() => {
|
||||
// ignore when column already exists
|
||||
});
|
||||
await dbRun(
|
||||
"ALTER TABLE route_mappings ADD COLUMN api_name TEXT NOT NULL DEFAULT ''",
|
||||
).catch(() => {
|
||||
// ignore when column already exists
|
||||
});
|
||||
// 迁移:将 # 前缀路由转为 enabled=0 并去掉前缀
|
||||
const hashRoutes = await dbAll<RouteRow>(
|
||||
"SELECT route_key, file_path, status_code FROM route_mappings WHERE route_key LIKE '#%'",
|
||||
);
|
||||
for (const row of hashRoutes) {
|
||||
const cleanKey = row.route_key.replace(/^#+/, "");
|
||||
await dbRun("DELETE FROM route_mappings WHERE route_key = ?", [row.route_key]);
|
||||
await dbRun(
|
||||
"INSERT OR IGNORE INTO route_mappings(route_key, file_path, status_code, enabled) VALUES(?, ?, ?, 0)",
|
||||
[cleanKey, row.file_path, row.status_code],
|
||||
);
|
||||
}
|
||||
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,
|
||||
alias TEXT NOT NULL DEFAULT ''
|
||||
)
|
||||
`);
|
||||
await dbRun(
|
||||
"ALTER TABLE mock_files ADD COLUMN alias TEXT NOT NULL DEFAULT ''",
|
||||
).catch(() => {
|
||||
// ignore when column already exists
|
||||
});
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS server_config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
// 清理不该出现在 mock 列表中的系统文件
|
||||
await dbRun(
|
||||
"DELETE FROM mock_files WHERE file_path = ? OR file_path LIKE ?",
|
||||
["mock/api-list.json", "%.sqlite3"],
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveRoutesToDb(
|
||||
routes: RouteConfig,
|
||||
routeStatuses: RouteStatusConfig = {},
|
||||
routeEnabledMap: RouteEnabledMap = {},
|
||||
routeApiNameMap: RouteApiNameMap = {},
|
||||
): Promise<void> {
|
||||
await dbRun("DELETE FROM route_mappings");
|
||||
for (const [routeKey, filePath] of Object.entries(routes)) {
|
||||
const statusCode = normalizeStatusCode(routeStatuses[routeKey], 200);
|
||||
const enabled = routeEnabledMap[routeKey] !== false ? 1 : 0;
|
||||
const apiName = routeApiNameMap[routeKey] || "";
|
||||
await dbRun(
|
||||
"INSERT INTO route_mappings(route_key, file_path, status_code, enabled, api_name) VALUES(?, ?, ?, ?, ?)",
|
||||
[routeKey, filePath, statusCode, enabled, apiName],
|
||||
);
|
||||
await dbRun("INSERT OR IGNORE INTO mock_files(file_path) VALUES(?)", [
|
||||
filePath,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadRoutesFromDb(): Promise<{
|
||||
routes: RouteConfig;
|
||||
routeStatuses: RouteStatusConfig;
|
||||
routeEnabledMap: RouteEnabledMap;
|
||||
routeApiNameMap: RouteApiNameMap;
|
||||
}> {
|
||||
const rows = await dbAll<RouteRow>(
|
||||
"SELECT route_key, file_path, status_code, enabled, api_name FROM route_mappings ORDER BY route_key ASC",
|
||||
);
|
||||
const routes: RouteConfig = {};
|
||||
const routeStatuses: RouteStatusConfig = {};
|
||||
const routeEnabledMap: RouteEnabledMap = {};
|
||||
const routeApiNameMap: RouteApiNameMap = {};
|
||||
for (const row of rows) {
|
||||
routes[row.route_key] = row.file_path;
|
||||
routeStatuses[row.route_key] = normalizeStatusCode(row.status_code, 200);
|
||||
routeEnabledMap[row.route_key] = row.enabled !== 0;
|
||||
if (row.api_name) {
|
||||
routeApiNameMap[row.route_key] = row.api_name;
|
||||
}
|
||||
}
|
||||
return { routes, routeStatuses, routeEnabledMap, routeApiNameMap };
|
||||
}
|
||||
|
||||
export 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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export 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 }));
|
||||
}
|
||||
|
||||
export async function insertApiItemToDb(item: ApiListItem): Promise<void> {
|
||||
await dbRun("INSERT INTO api_list(route, name) VALUES(?, ?)", [
|
||||
item.route,
|
||||
item.name,
|
||||
]);
|
||||
}
|
||||
|
||||
export async function updateApiItemInDb(
|
||||
oldRoute: string,
|
||||
item: ApiListItem,
|
||||
): Promise<void> {
|
||||
await dbRun("UPDATE api_list SET route = ?, name = ? WHERE route = ?", [
|
||||
item.route,
|
||||
item.name,
|
||||
oldRoute,
|
||||
]);
|
||||
}
|
||||
|
||||
export async function deleteApiItemFromDb(route: string): Promise<void> {
|
||||
await dbRun("DELETE FROM api_list WHERE route = ?", [route]);
|
||||
}
|
||||
|
||||
export async function upsertMockFilePathToDb(
|
||||
filePath: string,
|
||||
alias?: string,
|
||||
): Promise<void> {
|
||||
if (typeof alias === "string") {
|
||||
await dbRun(
|
||||
"INSERT INTO mock_files(file_path, alias) VALUES(?, ?) ON CONFLICT(file_path) DO UPDATE SET alias = excluded.alias",
|
||||
[filePath, alias],
|
||||
);
|
||||
return;
|
||||
}
|
||||
await dbRun("INSERT OR IGNORE INTO mock_files(file_path, alias) VALUES(?, '')", [
|
||||
filePath,
|
||||
]);
|
||||
}
|
||||
|
||||
export async function removeMockFilePathFromDb(filePath: string): Promise<void> {
|
||||
await dbRun("DELETE FROM mock_files WHERE file_path = ?", [filePath]);
|
||||
}
|
||||
|
||||
export async function loadMockFilePathsFromDb(): Promise<MockFileRow[]> {
|
||||
const rows = await dbAll<MockFileRow>(
|
||||
"SELECT file_path, alias FROM mock_files ORDER BY file_path ASC",
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
file_path: row.file_path,
|
||||
alias: String(row.alias || ""),
|
||||
}));
|
||||
}
|
||||
|
||||
const DEFAULT_SERVER_CONFIG: AppConfig = {
|
||||
cacheConfig: true,
|
||||
reloadOnChange: true,
|
||||
defaultContentType: "application/json",
|
||||
proxyPort: 8879,
|
||||
targetHost: "localhost",
|
||||
targetPort: 80,
|
||||
targetHttps: false,
|
||||
};
|
||||
|
||||
export async function loadServerConfig(): Promise<AppConfig> {
|
||||
const rows = await dbAll<{ key: string; value: string }>(
|
||||
"SELECT key, value FROM server_config",
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
return { ...DEFAULT_SERVER_CONFIG };
|
||||
}
|
||||
const map = new Map(rows.map((r) => [r.key, r.value]));
|
||||
return {
|
||||
mockEnabled: map.has("mockEnabled")
|
||||
? map.get("mockEnabled") === "true"
|
||||
: undefined,
|
||||
cacheConfig: map.get("cacheConfig") !== "false",
|
||||
reloadOnChange: map.get("reloadOnChange") !== "false",
|
||||
defaultContentType:
|
||||
map.get("defaultContentType") ||
|
||||
DEFAULT_SERVER_CONFIG.defaultContentType,
|
||||
proxyPort: Number(map.get("proxyPort")) || DEFAULT_SERVER_CONFIG.proxyPort,
|
||||
targetHost: map.get("targetHost") || DEFAULT_SERVER_CONFIG.targetHost,
|
||||
targetPort: Number(map.get("targetPort")) || DEFAULT_SERVER_CONFIG.targetPort,
|
||||
targetHttps: map.get("targetHttps") === "true",
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveServerConfig(config: AppConfig): Promise<void> {
|
||||
const entries: [string, string][] = [
|
||||
["mockEnabled", String(config.mockEnabled !== false)],
|
||||
["cacheConfig", String(config.cacheConfig)],
|
||||
["reloadOnChange", String(config.reloadOnChange)],
|
||||
["defaultContentType", config.defaultContentType],
|
||||
["proxyPort", String(config.proxyPort)],
|
||||
["targetHost", config.targetHost],
|
||||
["targetPort", String(config.targetPort ?? "")],
|
||||
["targetHttps", String(config.targetHttps !== false)],
|
||||
];
|
||||
await dbRun("DELETE FROM server_config");
|
||||
for (const [key, value] of entries) {
|
||||
await dbRun("INSERT INTO server_config(key, value) VALUES(?, ?)", [
|
||||
key,
|
||||
value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user