68 lines
2.1 KiB
JavaScript
68 lines
2.1 KiB
JavaScript
const db = require('../../database/database');
|
|
|
|
class I18nPreferencesRepository {
|
|
_safeJsonArray(value) {
|
|
if (Array.isArray(value)) return value;
|
|
if (value == null) return [];
|
|
|
|
try {
|
|
const parsed = typeof value === 'string' ? JSON.parse(value) : value;
|
|
return Array.isArray(parsed) ? parsed : [];
|
|
} catch (_) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
_normalizeRow(row) {
|
|
const categories = this._safeJsonArray(row?.categories_json);
|
|
const globalKeys = this._safeJsonArray(row?.global_keys_json);
|
|
return {
|
|
categories,
|
|
globalKeys,
|
|
};
|
|
}
|
|
|
|
async get() {
|
|
const [rows] = await db.query('SELECT * FROM i18n_preferences WHERE id = 1 LIMIT 1');
|
|
if (!rows.length) {
|
|
return { categories: [], globalKeys: [] };
|
|
}
|
|
return this._normalizeRow(rows[0]);
|
|
}
|
|
|
|
async upsert({ categories, globalKeys, updatedByUserId } = {}) {
|
|
const current = await this.get();
|
|
|
|
const nextCategories = categories !== undefined ? categories : current.categories;
|
|
const nextGlobalKeys = globalKeys !== undefined ? globalKeys : current.globalKeys;
|
|
|
|
await db.query(
|
|
`INSERT INTO i18n_preferences (id, categories_json, global_keys_json, updated_by_user_id)
|
|
VALUES (1, ?, ?, ?)
|
|
ON DUPLICATE KEY UPDATE
|
|
categories_json = VALUES(categories_json),
|
|
global_keys_json = VALUES(global_keys_json),
|
|
updated_by_user_id = VALUES(updated_by_user_id)`,
|
|
[JSON.stringify(nextCategories || []), JSON.stringify(nextGlobalKeys || []), updatedByUserId || null]
|
|
);
|
|
|
|
return this.get();
|
|
}
|
|
|
|
async clear(updatedByUserId) {
|
|
await db.query(
|
|
`INSERT INTO i18n_preferences (id, categories_json, global_keys_json, updated_by_user_id)
|
|
VALUES (1, ?, ?, ?)
|
|
ON DUPLICATE KEY UPDATE
|
|
categories_json = VALUES(categories_json),
|
|
global_keys_json = VALUES(global_keys_json),
|
|
updated_by_user_id = VALUES(updated_by_user_id)`,
|
|
[JSON.stringify([]), JSON.stringify([]), updatedByUserId || null]
|
|
);
|
|
|
|
return this.get();
|
|
}
|
|
}
|
|
|
|
module.exports = I18nPreferencesRepository;
|