53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import * as fs from "fs";
|
|
import { API_LIST_FILE } from "./constants";
|
|
import { loadApiListFromDb, upsertApiListToDb } from "./db";
|
|
import type { ApiListItem } from "./types";
|
|
|
|
function parseApiListFromJson(): 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 [];
|
|
}
|
|
}
|
|
|
|
// 一次性迁移:如果 DB 为空且 api-list.json 存在,导入到 DB
|
|
export async function migrateApiListFromJsonIfNeeded(): Promise<void> {
|
|
const dbList = await loadApiListFromDb();
|
|
if (dbList.length > 0) return;
|
|
const jsonList = parseApiListFromJson();
|
|
if (jsonList.length > 0) {
|
|
await upsertApiListToDb(jsonList);
|
|
console.log(
|
|
`[BOOTSTRAP] 已从 api-list.json 迁移 ${jsonList.length} 条接口到数据库`,
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function loadApiList(): Promise<ApiListItem[]> {
|
|
return loadApiListFromDb();
|
|
}
|