mirror of
https://github.com/imputnet/cobalt.git
synced 2024-12-28 18:46:09 +00:00
settings: add migrations, include schemaVersion in storage
This commit is contained in:
parent
6c9d759a3a
commit
2a0366a58d
|
@ -7,23 +7,46 @@ import type { CobaltSettings } from './types/settings';
|
|||
import defaultSettings from './settings/defaults';
|
||||
|
||||
type PartialSettings = RecursivePartial<CobaltSettings>;
|
||||
type PartialSettingsWithSchema = RecursivePartial<CobaltSettings> & { 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<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 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<CobaltSettings>) => void;
|
||||
|
|
Loading…
Reference in a new issue