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 LOCALES_FILE = path.join(__dirname, '../data/locales.json'); const LOCALES_DATA = {}; 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 initLocales = () => { Cache.getData(LOCALES_FILE).then(data => { Logs.out('load locales data', data); Object.assign(LOCALES_DATA, data); }).catch(error => { Logs.out('not load locales data', error.message); }); } const saveLocales = () => { Cache.setData(LOCALES_FILE, LOCALES_DATA).catch(error => { Logs.out('save cache failed', error); }); } export const get = async (keys) => { return new Promise((resolve, reject) => { if (typeof(keys) === 'undefined') { resolve(LOCALES_DATA); } else if (typeof(keys) === 'string') { resolve(LOCALES_DATA[keys] ?? null); } else if (Array.isArray(keys) && keys.every(key => typeof(key) === 'string')) { const result = {}; keys.forEach(key => { result[key] = LOCALES_DATA[key] ?? null; }); resolve(result); } else { reject(new Error('invalid keys')); } }); } export const set = async (key, value) => { return new Promise((resolve, reject) => { if (typeof(key) === 'string' && typeof(value) !== 'undefined') { LOCALES_DATA[key] = value; saveLocales(); resolve(); } else if (isPlainObject(key) && Object.keys(key).every(k => typeof(k) === 'string') && Object.values(key).every(v => typeof(v) === 'string')) { Object.assign(LOCALES_DATA, key); saveLocales(); resolve(); } else { reject(new Error('invalid key or value')); } }); } export const remove = async (keys) => { return new Promise((resolve, reject) => { if (typeof(keys) === 'string') { delete LOCALES_DATA[keys]; saveLocales(); resolve(); } else if (Array.isArray(keys) && keys.every(key => typeof(key) === 'string')) { keys.forEach(key => { delete LOCALES_DATA[key]; }); saveLocales(); resolve(); } else { reject(new Error('invalid keys')); } }); } // 进程结束时保存数据 process.on('exit', saveLocales); process.on('SIGINT', () => { process.exit(0); }); process.on('SIGTERM', () => { process.exit(0); }); process.on('SIGUSR2', () => { process.exit(0); }); // 初始化缓存 initLocales(); export default { get, set, remove };