| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- 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 };
|