settings: add migrations, include schemaVersion in storage

This commit is contained in:
dumbmoron 2024-07-13 12:05:52 +00:00
parent 6c9d759a3a
commit 2a0366a58d
No known key found for this signature in database

View file

@ -7,23 +7,46 @@ import type { CobaltSettings } from './types/settings';
import defaultSettings from './settings/defaults'; import defaultSettings from './settings/defaults';
type PartialSettings = RecursivePartial<CobaltSettings>; type PartialSettings = RecursivePartial<CobaltSettings>;
type PartialSettingsWithSchema = RecursivePartial<CobaltSettings> & { schemaVersion: number };
const writeToStorage = (settings: PartialSettings) => { const writeToStorage = (settings: PartialSettings) => {
localStorage.setItem( localStorage.setItem(
"settings", "settings",
JSON.stringify(settings) JSON.stringify({
schemaVersion: defaultSettings.schemaVersion,
...settings
})
); );
return settings; return settings;
} }
type Migrator = (s: PartialSettings) => PartialSettings;
const migrations: Record<number, Migrator> = {
}
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 loadFromStorage = () => {
const settings = localStorage.getItem('settings'); const settings = localStorage.getItem('settings');
if (!settings) { if (!settings) {
return {}; 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<CobaltSettings>) => void; let update: (_: Updater<CobaltSettings>) => void;