214 lines
5.9 KiB
JavaScript
214 lines
5.9 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* 轻量 JSON 持久化存储。
|
|
*
|
|
* - 所有运行时数据都保存在 data/ 目录(可通过 DATA_DIR 环境变量覆盖),
|
|
* 不会写死在源代码里。
|
|
* - 写入使用「临时文件 + rename」的原子方式,避免进程中断留下半个 JSON。
|
|
* - 文件损坏时自动备份为 *.corrupt-<时间戳>.bak 并使用种子数据重建。
|
|
* - 每个文件带有 schemaVersion,方便以后做数据迁移。
|
|
*/
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { randomUUID } = require('crypto');
|
|
|
|
const SCHEMA_VERSION = 1;
|
|
|
|
function nowIso() {
|
|
return new Date().toISOString();
|
|
}
|
|
|
|
function clone(value) {
|
|
return JSON.parse(JSON.stringify(value));
|
|
}
|
|
|
|
function atomicWriteJson(filePath, value) {
|
|
const dir = path.dirname(filePath);
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
const text = JSON.stringify(value, null, 2) + '\n';
|
|
const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
fs.writeFileSync(tmp, text, 'utf8');
|
|
try {
|
|
fs.renameSync(tmp, filePath);
|
|
} catch (err) {
|
|
try { fs.unlinkSync(tmp); } catch (_) { /* ignore */ }
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
function backupCorrupt(filePath) {
|
|
try {
|
|
const backup = `${filePath}.corrupt-${Date.now()}.bak`;
|
|
fs.copyFileSync(filePath, backup);
|
|
console.error(`[store] ${path.basename(filePath)} 无法解析,已备份到 ${path.basename(backup)}`);
|
|
} catch (err) {
|
|
console.error(`[store] 备份损坏文件失败: ${err.message}`);
|
|
}
|
|
}
|
|
|
|
function readJsonFile(filePath) {
|
|
const raw = fs.readFileSync(filePath, 'utf8');
|
|
return JSON.parse(raw);
|
|
}
|
|
|
|
/** 通用 JSON 文档(对象) */
|
|
class JsonDocument {
|
|
constructor(filePath, defaultValue) {
|
|
this.filePath = filePath;
|
|
this.defaultValue = clone(defaultValue);
|
|
this.value = clone(defaultValue);
|
|
this.loaded = false;
|
|
this.load();
|
|
}
|
|
|
|
load() {
|
|
try {
|
|
const parsed = readJsonFile(this.filePath);
|
|
if (parsed && typeof parsed === 'object' && parsed.data && typeof parsed.data === 'object') {
|
|
this.value = { ...clone(this.defaultValue), ...parsed.data };
|
|
} else if (parsed && typeof parsed === 'object') {
|
|
this.value = { ...clone(this.defaultValue), ...parsed };
|
|
}
|
|
this.loaded = true;
|
|
} catch (err) {
|
|
if (err.code !== 'ENOENT') backupCorrupt(this.filePath);
|
|
this.value = clone(this.defaultValue);
|
|
this.loaded = false;
|
|
this.save();
|
|
}
|
|
}
|
|
|
|
save() {
|
|
atomicWriteJson(this.filePath, {
|
|
schemaVersion: SCHEMA_VERSION,
|
|
updatedAt: nowIso(),
|
|
data: this.value,
|
|
});
|
|
}
|
|
|
|
update(patch) {
|
|
this.value = { ...this.value, ...patch };
|
|
this.save();
|
|
return this.value;
|
|
}
|
|
}
|
|
|
|
/** 通用 JSON 集合(数组) */
|
|
class JsonCollection {
|
|
/**
|
|
* @param {string} filePath
|
|
* @param {{ seed?: any[], normalize?: (item:any)=>any, idPrefix?: string }} options
|
|
*/
|
|
constructor(filePath, options = {}) {
|
|
this.filePath = filePath;
|
|
this.seed = clone(options.seed || []);
|
|
this.normalize = options.normalize || ((item) => item);
|
|
this.items = [];
|
|
this.load();
|
|
}
|
|
|
|
load() {
|
|
try {
|
|
const parsed = readJsonFile(this.filePath);
|
|
const rawItems = Array.isArray(parsed) ? parsed : (Array.isArray(parsed.items) ? parsed.items : null);
|
|
if (!rawItems) throw new Error('数据格式不是数组');
|
|
this.items = rawItems.map((item) => this.safeNormalize(item)).filter(Boolean);
|
|
} catch (err) {
|
|
if (err.code !== 'ENOENT') backupCorrupt(this.filePath);
|
|
this.items = this.seed.map((item) => this.safeNormalize(item)).filter(Boolean);
|
|
this.save();
|
|
}
|
|
}
|
|
|
|
safeNormalize(item) {
|
|
try {
|
|
return this.normalize(item);
|
|
} catch (err) {
|
|
console.error(`[store] 忽略无效数据 (${path.basename(this.filePath)}): ${err.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
save() {
|
|
atomicWriteJson(this.filePath, {
|
|
schemaVersion: SCHEMA_VERSION,
|
|
updatedAt: nowIso(),
|
|
items: this.items,
|
|
});
|
|
}
|
|
|
|
list() {
|
|
return this.items;
|
|
}
|
|
|
|
find(id) {
|
|
return this.items.find((item) => item.id === id) || null;
|
|
}
|
|
|
|
insert(item) {
|
|
const created = this.safeNormalize({ ...item, id: item.id || this.newId() });
|
|
if (!created) throw new Error('数据校验失败');
|
|
this.items.push(created);
|
|
this.save();
|
|
return created;
|
|
}
|
|
|
|
update(id, patch) {
|
|
const idx = this.items.findIndex((item) => item.id === id);
|
|
if (idx === -1) return null;
|
|
const merged = this.safeNormalize({ ...this.items[idx], ...patch, id });
|
|
if (!merged) throw new Error('数据校验失败');
|
|
this.items[idx] = merged;
|
|
this.save();
|
|
return merged;
|
|
}
|
|
|
|
remove(id) {
|
|
const before = this.items.length;
|
|
this.items = this.items.filter((item) => item.id !== id);
|
|
if (this.items.length === before) return false;
|
|
this.save();
|
|
return true;
|
|
}
|
|
|
|
newId() {
|
|
return `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 初始化全部存储。
|
|
* @param {string} dataDir
|
|
* @param {{ appearancePresets: any[], contentPresets: any[], lrcPresets: any[], settings: any }} seed
|
|
*/
|
|
function createStores(dataDir, seed) {
|
|
fs.mkdirSync(dataDir, { recursive: true });
|
|
return {
|
|
dataDir,
|
|
appearancePresets: new JsonCollection(path.join(dataDir, 'appearance-presets.json'), {
|
|
seed: seed.appearancePresets,
|
|
normalize: seed.normalizeAppearancePreset,
|
|
}),
|
|
contentPresets: new JsonCollection(path.join(dataDir, 'content-presets.json'), {
|
|
seed: seed.contentPresets,
|
|
normalize: seed.normalizeContentPreset,
|
|
}),
|
|
lrcPresets: new JsonCollection(path.join(dataDir, 'lrc-presets.json'), {
|
|
seed: seed.lrcPresets,
|
|
normalize: seed.normalizeLrcPreset,
|
|
}),
|
|
settings: new JsonDocument(path.join(dataDir, 'settings.json'), seed.settings),
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
SCHEMA_VERSION,
|
|
JsonDocument,
|
|
JsonCollection,
|
|
createStores,
|
|
atomicWriteJson,
|
|
readJsonFile,
|
|
};
|