From 2a0366a58d06c9bcf29b0053d58f9d04f16f3712 Mon Sep 17 00:00:00 2001 From: dumbmoron Date: Sat, 13 Jul 2024 12:05:52 +0000 Subject: [PATCH] settings: add migrations, include schemaVersion in storage --- web/src/lib/settings.ts | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/web/src/lib/settings.ts b/web/src/lib/settings.ts index 436ca209..c09f1f6b 100644 --- a/web/src/lib/settings.ts +++ b/web/src/lib/settings.ts @@ -7,23 +7,46 @@ import type { CobaltSettings } from './types/settings'; import defaultSettings from './settings/defaults'; type PartialSettings = RecursivePartial; +type PartialSettingsWithSchema = RecursivePartial & { schemaVersion: number }; const writeToStorage = (settings: PartialSettings) => { localStorage.setItem( "settings", - JSON.stringify(settings) + JSON.stringify({ + schemaVersion: defaultSettings.schemaVersion, + ...settings + }) ); return settings; } +type Migrator = (s: PartialSettings) => PartialSettings; +const migrations: Record = { + +} + +const migrate = (settings: PartialSettingsWithSchema) => { + return Object.keys(migrations) + .map(Number) + .filter(version => version > settings.schemaVersion) + .reduce((settings, migrationVersion) => { + return migrations[migrationVersion](settings); + }, settings as PartialSettings); +} + const loadFromStorage = () => { const settings = localStorage.getItem('settings'); if (!settings) { return {}; } - return JSON.parse(settings) as PartialSettings; + const parsed = JSON.parse(settings) as PartialSettingsWithSchema; + if (parsed.schemaVersion < defaultSettings.schemaVersion) { + return migrate(parsed); + } + + return parsed; } let update: (_: Updater) => void;