Skip to content

Commit

Permalink
Add auto backup for configs
Browse files Browse the repository at this point in the history
  • Loading branch information
guansss committed Mar 5, 2020
1 parent 98e99ef commit fa40dd7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
9 changes: 2 additions & 7 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,8 @@ function startup() {
startup();
});

// completely reset!
app.once('reset', () => {
mainApp.$destroy();
app.destroy();
localStorage.clear();
startup();
});
// reload after resetting
app.once('reset', () => setTimeout(() => app.emit('reload'), 0));

Modules.forEach(Module => app.use(Module));

Expand Down
20 changes: 17 additions & 3 deletions src/module/config/ConfigModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export interface App {

on(event: 'config', fn: (path: string, value: any, runtime?: boolean) => void, context?: any): this;

emit(event: 'init'): this;
emit(event: 'init', prevVersion: string | undefined, config: Config): this;

emit(event: 'configReady', config: Config): this;

Expand All @@ -61,7 +61,7 @@ export default class ConfigModule implements Module {
constructor(readonly app: App) {
this.read();

app.on('config', this.setConfig, this);
app.on('config', this.setConfig, this).on('reset', this.reset, this);

app.sticky('configReady', this.config);

Expand All @@ -74,6 +74,8 @@ export default class ConfigModule implements Module {
if (!prevVersion) {
// inherit volume from old 1.x versions
app.once('we:volume', (value: number) => app.emit('config', 'volume', value / 10));
} else {
this.backup(prevVersion);
}

app.sticky('init', prevVersion);
Expand Down Expand Up @@ -101,12 +103,13 @@ export default class ConfigModule implements Module {
}

/**
* A handy method for batching queries.
* @param receiver
* @param pairs - Pairs of path and default value.
* @example
* getConfigs(receiver, 'obj.number', 0, 'obj.bool', false)
*/
getConfigs(receiver: (path: string, value: any) => void, pairs: any[]) {
getConfigs(receiver: (path: string, value: any) => void, pairs: string | any[]) {
for (let i = 0; i < pairs.length; i += 2) {
receiver(pairs[i], this.getConfig(pairs[i] as string, pairs[i + 1]));
}
Expand Down Expand Up @@ -135,4 +138,15 @@ export default class ConfigModule implements Module {
}
return false;
}

backup(version: string) {
localStorage.setItem(this.storageKey + '-' + version, localStorage.getItem(this.storageKey) || '');
}

reset() {
this.backup(localStorage.v);

localStorage.removeItem('v');
localStorage.removeItem(this.storageKey);
}
}

0 comments on commit fa40dd7

Please sign in to comment.