Files
2026-11-23 08:03:06 +00:00

25 lines
1.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 伺服器啟動時決定資料存在哪裡。
// - 有 COST_MODEL_DATA_DIR:預設存進 <資料夾>/leadboard.db(SQLite);STORAGE_BACKEND=json 可以退回舊的 JSON 檔。
// - 第一次用資料庫(import_log 沒有成功紀錄)時,自動把資料夾裡現有的 JSON 搬進去並逐筆核對;
// 核對不過就啟動失敗(寧可不上線,也不讓大家看到一份空的或錯的資料)。JSON 檔不會被動到。
import { resolve } from 'node:path';
import { openDatabase } from './db.js';
import { importJson, formatReport } from './import-json.js';
import { fileStorage, sqliteStorage } from './storage.js';
export function openDataStorage(dir, { backend = process.env.STORAGE_BACKEND, log = console } = {}) {
if (!dir) return null;
if (String(backend || 'sqlite').toLowerCase() === 'json') {
log.warn?.('storage: STORAGE_BACKEND=json,資料存在 JSON 檔');
return fileStorage(dir);
}
const db = openDatabase(resolve(dir, 'leadboard.db'));
const done = db.prepare('SELECT COUNT(*) AS n FROM import_log WHERE ok = 1').get().n;
if (!done) {
const result = importJson({ dir, db });
log.log?.(`storage: 第一次使用 leadboard.db,匯入既有 JSON\n${formatReport(result)}`);
if (!result.ok) { db.close(); throw new Error('storage: JSON 匯入核對未通過,不啟動(JSON 檔未動,資料庫已有的內容也未被覆蓋)'); }
}
return sqliteStorage(db);
}