1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

storage-helper refactoring

Signed-off-by: Roman <ixrock@gmail.com>
This commit is contained in:
Roman 2021-05-07 14:10:04 +03:00
parent 81a6b3ce17
commit d4d03532d7
3 changed files with 62 additions and 47 deletions

View File

@ -1,9 +1,8 @@
import { useState } from "react"; import { useState } from "react";
import { createStorage } from "../utils"; import { createStorage } from "../utils";
import { CreateObservableOptions } from "mobx";
export function useStorage<T>(key: string, initialValue: T, options?: CreateObservableOptions) { export function useStorage<T>(key: string, initialValue: T) {
const storage = createStorage(key, initialValue, options); const storage = createStorage(key, initialValue);
const [storageValue, setStorageValue] = useState(storage.get()); const [storageValue, setStorageValue] = useState(storage.get());
const setValue = (value: T) => { const setValue = (value: T) => {
setStorageValue(value); setStorageValue(value);

View File

@ -2,68 +2,90 @@
// Because app creates random port between restarts => storage session wiped out each time. // Because app creates random port between restarts => storage session wiped out each time.
import path from "path"; import path from "path";
import { app, remote } from "electron"; import { app, remote } from "electron";
import { observable, reaction, when, CreateObservableOptions } from "mobx"; import { comparer, observable, reaction, toJS, when } from "mobx";
import fse from "fs-extra"; import fse from "fs-extra";
import { StorageHelper } from "./storageHelper"; import { StorageHelper } from "./storageHelper";
import { ClusterStore, getHostedClusterId } from "../../common/cluster-store"; import { ClusterStore, getHostedClusterId } from "../../common/cluster-store";
import logger from "../../main/logger"; import logger from "../../main/logger";
let initialized = false; const LOG_PREFIX = '[LocalStorageHelper]:';
const loaded = observable.box(false);
const storage = observable.map<string/* key */, any /* serializable */>();
export function createStorage<T>(key: string, defaultValue: T, observableOptions?: CreateObservableOptions) { const storage = observable({
initialized: false,
loaded: false,
data: {} as { [key: string]: any }, // json-compatible state
});
/**
* Creates a helper for saving data under the "key" intended for window.localStorage
* @param key
* @param defaultValue
*/
export function createStorage<T>(key: string, defaultValue: T) {
const clusterId = getHostedClusterId(); const clusterId = getHostedClusterId();
const savingFolder = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage"); const folder = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage");
const jsonFilePath = path.resolve(savingFolder, `${clusterId ?? "app"}.json`); const fileName = `${clusterId ?? "app"}.json`;
const filePath = path.resolve(folder, fileName);
if (!initialized) { if (!storage.initialized) {
initialized = true; init(); // called once per cluster-view
}
// read once per cluster domain function init() {
fse.readJson(jsonFilePath) storage.initialized = true;
.then((data = {}) => storage.merge(data))
// read previously saved state (if any)
fse.readJson(filePath)
.then(data => storage.data = data)
.catch(() => null) // ignore empty / non-existing / invalid json files .catch(() => null) // ignore empty / non-existing / invalid json files
.finally(() => loaded.set(true)); .finally(() => {
logger.info(`${LOG_PREFIX} loaded local-storage file "${filePath}"`);
storage.loaded = true;
});
// bind auto-saving // bind auto-saving data changes to %storage-file.json
reaction(() => storage.toJSON(), saveFile, { delay: 250 }); reaction(() => toJS(storage.data), saveFile, {
delay: 250, // lazy, avoid excessive writes to fs
equals: comparer.structural, // save only when something really changed
});
// remove json-file when cluster deleted // remove json-file when cluster deleted
if (clusterId !== undefined) { if (clusterId !== undefined) {
when(() => ClusterStore.getInstance(false)?.removedClusters.has(clusterId)).then(removeFile); when(() => ClusterStore.getInstance(false)?.removedClusters.has(clusterId)).then(removeFile);
} }
}
async function saveFile(json = {}) { async function saveFile(state: Record<string, any> = {}) {
try { logger.info(`${LOG_PREFIX} saving ${filePath}`);
await fse.ensureDir(savingFolder, { mode: 0o755 }); try {
await fse.writeJson(jsonFilePath, json, { spaces: 2 }); await fse.ensureDir(folder, { mode: 0o755 });
} catch (error) { await fse.writeJson(filePath, state, { spaces: 2 });
logger.error(`[save]: ${error}`, { json, jsonFilePath }); } catch (error) {
logger.error(`${LOG_PREFIX} saving failed: ${error}`, {
json: state, jsonFilePath: filePath
});
}
} }
}
function removeFile() { function removeFile() {
logger.debug("[remove]:", jsonFilePath); logger.debug(`${LOG_PREFIX} removing ${filePath}`);
fse.unlink(jsonFilePath).catch(Function); fse.unlink(filePath).catch(Function);
}
} }
return new StorageHelper<T>(key, { return new StorageHelper<T>(key, {
autoInit: true, autoInit: true,
observable: observableOptions,
defaultValue, defaultValue,
storage: { storage: {
async getItem(key: string) { async getItem(key: string) {
await when(() => loaded.get()); await when(() => storage.loaded);
return storage.get(key); return storage.data[key];
}, },
setItem(key: string, value: any) { setItem(key: string, value: any) {
storage.set(key, value); storage.data[key] = value;
}, },
removeItem(key: string) { removeItem(key: string) {
storage.delete(key); delete storage.data[key];
} }
}, },
}); });

View File

@ -1,6 +1,6 @@
// Helper for working with storages (e.g. window.localStorage, NodeJS/file-system, etc.) // Helper for working with storages (e.g. window.localStorage, NodeJS/file-system, etc.)
import { action, comparer, CreateObservableOptions, IObservableValue, makeObservable, observable, toJS, when, } from "mobx"; import { action, CreateObservableOptions, IObservableValue, makeObservable, observable, toJS, when, } from "mobx";
import produce, { Draft } from "immer"; import produce, { Draft } from "immer";
import { isEqual, isFunction, isPlainObject } from "lodash"; import { isEqual, isFunction, isPlainObject } from "lodash";
import logger from "../../main/logger"; import logger from "../../main/logger";
@ -15,7 +15,6 @@ export interface StorageAdapter<T> {
export interface StorageHelperOptions<T> { export interface StorageHelperOptions<T> {
autoInit?: boolean; // start preloading data immediately, default: true autoInit?: boolean; // start preloading data immediately, default: true
observable?: CreateObservableOptions;
storage: StorageAdapter<T>; storage: StorageAdapter<T>;
defaultValue: T; defaultValue: T;
} }
@ -23,10 +22,6 @@ export interface StorageHelperOptions<T> {
export class StorageHelper<T> { export class StorageHelper<T> {
static readonly defaultOptions: Partial<StorageHelperOptions<any>> = { static readonly defaultOptions: Partial<StorageHelperOptions<any>> = {
autoInit: true, autoInit: true,
observable: {
deep: true,
equals: comparer.shallow,
}
}; };
private data: IObservableValue<T>; private data: IObservableValue<T>;
@ -38,16 +33,14 @@ export class StorageHelper<T> {
constructor(readonly key: string, private options: StorageHelperOptions<T>) { constructor(readonly key: string, private options: StorageHelperOptions<T>) {
makeObservable(this); makeObservable(this);
this.data = observable.box<T>(this.options.defaultValue, {
...StorageHelper.defaultOptions.observable,
...(options.observable ?? {})
});
this.data.observe_(({ newValue, oldValue }) => {
this.onChange(newValue as T, oldValue as T);
});
this.storage = options.storage; this.storage = options.storage;
this.defaultValue = options.defaultValue; this.defaultValue = options.defaultValue;
this.data = observable.box<T>(this.defaultValue);
this.data.observe_(({ newValue, oldValue }) => {
this.onChange(newValue as T, oldValue as T);
});
if (this.options.autoInit) { if (this.options.autoInit) {
this.init(); this.init();
@ -126,6 +119,7 @@ export class StorageHelper<T> {
this.data.set(this.defaultValue); this.data.set(this.defaultValue);
} }
@action
merge(value: Partial<T> | ((draft: Draft<T>) => Partial<T> | void)) { merge(value: Partial<T> | ((draft: Draft<T>) => Partial<T> | void)) {
const nextValue = produce(this.get(), (state: Draft<T>) => { const nextValue = produce(this.get(), (state: Draft<T>) => {
const newValue = isFunction(value) ? value(state) : value; const newValue = isFunction(value) ? value(state) : value;