system-settings.js (2690B)
1 import { 2 applyBrandingPatch, 3 hasBrandingPatch, 4 normalizeBrandingObject, 5 normalizeBrandingPatch, 6 serializeBranding, 7 } from './admin-branding.js'; 8 import { HttpError } from './http/http-error.js'; 9 10 const ALLOWED_FIELDS = new Set(['logo_url', 'primary_color']); 11 12 function invalidRequest(message) { 13 return new HttpError(400, 'invalid_request', message); 14 } 15 16 function isPlainObject(value) { 17 return value !== null && typeof value === 'object' && !Array.isArray(value); 18 } 19 20 function serializeSettings(row) { 21 return { 22 ...serializeBranding(row.branding), 23 updated_at: row.updated_at, 24 }; 25 } 26 27 export function normalizeSystemSettingsPatch(body) { 28 if (!isPlainObject(body)) { 29 throw invalidRequest('Request body must be a JSON object'); 30 } 31 32 for (const field of Object.keys(body)) { 33 if (!ALLOWED_FIELDS.has(field)) { 34 throw invalidRequest(`Unknown field: ${field}`); 35 } 36 } 37 38 if (Object.keys(body).length === 0) { 39 throw invalidRequest('At least one setting must be provided'); 40 } 41 42 return normalizeBrandingPatch(body); 43 } 44 45 async function loadSystemSettingsRow(systemDb) { 46 const row = await systemDb.get( 47 `SELECT branding, created_at, updated_at 48 FROM system_settings 49 WHERE id = 1` 50 ); 51 if (row) return row; 52 53 const now = Date.now(); 54 await systemDb.run( 55 `INSERT INTO system_settings 56 (id, branding, created_at, updated_at) 57 VALUES 58 (1, '{}', {createdAt}, {updatedAt})`, 59 { createdAt: now, updatedAt: now } 60 ); 61 62 const created = await systemDb.get( 63 `SELECT branding, created_at, updated_at 64 FROM system_settings 65 WHERE id = 1` 66 ); 67 if (!created) { 68 throw new HttpError(500, 'internal_error', 'System settings are unavailable'); 69 } 70 return created; 71 } 72 73 export async function getSystemBranding(systemDb) { 74 const row = await loadSystemSettingsRow(systemDb); 75 return normalizeBrandingObject(row.branding); 76 } 77 78 export async function getAdminSystemSettings(systemDb) { 79 const row = await loadSystemSettingsRow(systemDb); 80 return serializeSettings(row); 81 } 82 83 export async function updateAdminSystemSettings({ systemDb, body, now = Date.now() }) { 84 const input = normalizeSystemSettingsPatch(body); 85 86 return systemDb.transaction(async (tx) => { 87 const current = await loadSystemSettingsRow(tx); 88 const branding = hasBrandingPatch(input) 89 ? applyBrandingPatch(current.branding, input) 90 : current.branding; 91 92 await tx.run( 93 `UPDATE system_settings 94 SET branding = {branding}, 95 updated_at = {now} 96 WHERE id = 1`, 97 { branding, now } 98 ); 99 100 const updated = await loadSystemSettingsRow(tx); 101 return serializeSettings(updated); 102 }); 103 }