Files
2026-10-29 11:57:29 +01:00

75 lines
2.9 KiB
JavaScript

// Generated, do not edit. sha256:816fe4fc80fac9d9927e815f090b57c44b134b1e4cc673a3ba8e1be8e308842d
import * as db from '../db.js';
import { PREFERENCES } from '../../shared/config.js';
import { assertEnum } from './_shared.js';
import { getBaseCurrency } from './portfolio.js';
import { fail } from '../../shared/app-error.js';
import { installLocale, setInstallLocale } from '../installation.mjs';
function prefSpec(scope, key) {
const s = PREFERENCES[scope];
if (!s) return undefined;
return s[key] || s['*'];
}
export function getPref(scope, key, fallback = undefined) {
const spec = prefSpec(scope, key);
const row = db.one(`SELECT value FROM Preference WHERE scope = ? AND key = ?`, [scope, key]);
if (row) {
const v = JSON.parse(row.value);
if (spec && spec.type === 'enum' && Array.isArray(spec.allowed) && !spec.allowed.includes(v)) return spec.initial;
return v;
}
return spec ? spec.initial : fallback;
}
export async function setPref(scope, key, value) {
const spec = prefSpec(scope, key);
if (spec) {
if (spec.type === 'enum') assertEnum(`${scope}.${key}`, spec.allowed, value);
else if (spec.type === 'bool') {
value = Number(value);
if (value !== 0 && value !== 1) fail('settings.prefBadValue', { scope, key, waarde: value }, `Invalid value for ${scope}.${key}: ${value}.`);
}
else if (spec.type === 'int') {
value = Number(value);
if (!Number.isInteger(value)) fail('settings.prefWantsInteger', { scope, key, waarde: value }, `Invalid value for ${scope}.${key}: ${value} (an integer was expected).`);
if (spec.min != null && value < spec.min) fail('settings.prefBelowMin', { scope, key, min: spec.min }, `${scope}.${key} may not be smaller than ${spec.min}.`);
if (spec.max != null && value > spec.max) fail('settings.prefAboveMax', { scope, key, max: spec.max }, `${scope}.${key} may not be greater than ${spec.max}.`);
}
}
db.run(`INSERT INTO Preference (scope, key, value) VALUES (?,?,?)
ON CONFLICT(scope, key) DO UPDATE SET value = excluded.value`,
[scope, key, JSON.stringify(value)]);
await db.persist();
}
export function getSettings() {
const out = {};
for (const [key] of Object.entries(PREFERENCES.app)) {
out[key] = getPref('app', key);
}
out.locale = installLocale();
out.version = db.schemaVersion();
out.baseCurrency = getBaseCurrency();
return out;
}
export async function updateSettings(patch) {
for (const [key, value] of Object.entries(patch)) {
if (value === undefined) continue;
if (key === 'locale') { setInstallLocale(value); continue; }
if (!PREFERENCES.app[key]) fail('settings.unknownSetting', { key }, `Unknown setting: ${key}.`);
await setPref('app', key, value);
}
}
export function forgetPrefRow(scope, key) {
db.run(`DELETE FROM Preference WHERE scope = ? AND key = ?`, [scope, key]);
}
export async function deletePref(scope, key) {
forgetPrefRow(scope, key);
await db.persist();
}