mirror of
https://github.com/wukko/cobalt.git
synced 2024-11-15 12:50:01 +00:00
settings: add migrations, include schemaVersion in storage
This commit is contained in:
parent
6c9d759a3a
commit
2a0366a58d
1 changed files with 25 additions and 2 deletions
|
@ -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;
|
||||||
|
|
Loading…
Reference in a new issue