import path from "path"; import { fileURLToPath } from "url"; import Logs from "../libs/logs.js"; import Cache from "../libs/cache.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const STORE_FILE = path.join(__dirname, '../data/store.json'); const STORE_DATA = {}; const STORE_OPTIONS = { saveVersion: 0, updateVersion: 0, }; /** * 判断是否为普通对象 * @param {*} obj * @returns */ const isPlainObject = (obj) => { if (Object.prototype.toString.call(obj) !== '[object Object]') return false; const proto = Object.getPrototypeOf(obj); return proto === Object.prototype || proto === null; } /** * 初始化数据 */ const initStore = () => { Cache.getData(STORE_FILE).then(data => { Logs.out('load store data', data); Object.assign(STORE_DATA, data); }).catch(error => { Logs.out('not load store data', error.message); }); } /** * 保存数据 */ const saveStore = () => { Cache.setData(STORE_FILE, STORE_DATA, 0).catch(error => { Logs.out('save cache failed', error); }); } /** * 获取数据 * @param {*} key * @param {*} property */ export const get = (key, property) => { if (!key) { return STORE_DATA; } if (property) { return STORE_DATA[property]?.[key] ?? null; } return STORE_DATA[key] ?? null; } /** * 设置数据 * @param {*} key * @param {*} value * @param {*} property */ export const set = (key, value, property) => { if (typeof(key) == 'string' && typeof(value) != 'undefined') { if (property && typeof(property) == 'string') { if (!STORE_DATA[property]) { STORE_DATA[property] = {}; } STORE_DATA[property][key] = value; } else { STORE_DATA[key] = value; } STORE_OPTIONS.updateVersion = Date.now(); } else if (isPlainObject(key)) { if (value && typeof(value) == 'string') { property = value; value = key; if (!STORE_DATA[property]) { STORE_DATA[property] = {}; } Object.assign(STORE_DATA[property], value); } else { value = key; Object.assign(STORE_DATA, value); } STORE_OPTIONS.updateVersion = Date.now(); } else { Logs.out('invalid key or value', key, value); } } export const remove = (key, property) => { if (property && STORE_DATA[property]) { delete STORE_DATA[property][key]; } else if (!property) { delete STORE_DATA[key]; } STORE_OPTIONS.updateVersion = Date.now(); } /** * 自动保存数据 */ const autoSaveStore = () => { if (STORE_OPTIONS.updateVersion > STORE_OPTIONS.saveVersion) { saveStore(); STORE_OPTIONS.saveVersion = STORE_OPTIONS.updateVersion; } setTimeout(() => { autoSaveStore(); }, 1000 * 60); } /** * 进程结束时保存数据 */ process.on('exit', saveStore); process.on('SIGINT', () => { process.exit(0); }); process.on('SIGTERM', () => { process.exit(0); }); process.on('SIGUSR2', () => { process.exit(0); }); // 初始化缓存 initStore(); // 自动保存数据 autoSaveStore(); export default { get, set, remove };