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 { createStorage } from "../utils";
import { CreateObservableOptions } from "mobx";
export function useStorage<T>(key: string, initialValue: T, options?: CreateObservableOptions) {
const storage = createStorage(key, initialValue, options);
export function useStorage<T>(key: string, initialValue: T) {
const storage = createStorage(key, initialValue);
const [storageValue, setStorageValue] = useState(storage.get());
const setValue = (value: T) => {
setStorageValue(value);

View File

@ -2,68 +2,90 @@
// Because app creates random port between restarts => storage session wiped out each time.
import path from "path";
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 { StorageHelper } from "./storageHelper";
import { ClusterStore, getHostedClusterId } from "../../common/cluster-store";
import logger from "../../main/logger";
let initialized = false;
const loaded = observable.box(false);
const storage = observable.map<string/* key */, any /* serializable */>();
const LOG_PREFIX = '[LocalStorageHelper]:';
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 savingFolder = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage");
const jsonFilePath = path.resolve(savingFolder, `${clusterId ?? "app"}.json`);
const folder = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage");
const fileName = `${clusterId ?? "app"}.json`;
const filePath = path.resolve(folder, fileName);
if (!initialized) {
initialized = true;
if (!storage.initialized) {
init(); // called once per cluster-view
}
// read once per cluster domain
fse.readJson(jsonFilePath)
.then((data = {}) => storage.merge(data))
function init() {
storage.initialized = true;
// read previously saved state (if any)
fse.readJson(filePath)
.then(data => storage.data = data)
.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
reaction(() => storage.toJSON(), saveFile, { delay: 250 });
// bind auto-saving data changes to %storage-file.json
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
if (clusterId !== undefined) {
when(() => ClusterStore.getInstance(false)?.removedClusters.has(clusterId)).then(removeFile);
}
}
async function saveFile(json = {}) {
try {
await fse.ensureDir(savingFolder, { mode: 0o755 });
await fse.writeJson(jsonFilePath, json, { spaces: 2 });
} catch (error) {
logger.error(`[save]: ${error}`, { json, jsonFilePath });
async function saveFile(state: Record<string, any> = {}) {
logger.info(`${LOG_PREFIX} saving ${filePath}`);
try {
await fse.ensureDir(folder, { mode: 0o755 });
await fse.writeJson(filePath, state, { spaces: 2 });
} catch (error) {
logger.error(`${LOG_PREFIX} saving failed: ${error}`, {
json: state, jsonFilePath: filePath
});
}
}
}
function removeFile() {
logger.debug("[remove]:", jsonFilePath);
fse.unlink(jsonFilePath).catch(Function);
function removeFile() {
logger.debug(`${LOG_PREFIX} removing ${filePath}`);
fse.unlink(filePath).catch(Function);
}
}
return new StorageHelper<T>(key, {
autoInit: true,
observable: observableOptions,
defaultValue,
storage: {
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) {
storage.set(key, value);
storage.data[key] = value;
},
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.)
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 { isEqual, isFunction, isPlainObject } from "lodash";
import logger from "../../main/logger";
@ -15,7 +15,6 @@ export interface StorageAdapter<T> {
export interface StorageHelperOptions<T> {
autoInit?: boolean; // start preloading data immediately, default: true
observable?: CreateObservableOptions;
storage: StorageAdapter<T>;
defaultValue: T;
}
@ -23,10 +22,6 @@ export interface StorageHelperOptions<T> {
export class StorageHelper<T> {
static readonly defaultOptions: Partial<StorageHelperOptions<any>> = {
autoInit: true,
observable: {
deep: true,
equals: comparer.shallow,
}
};
private data: IObservableValue<T>;
@ -38,16 +33,14 @@ export class StorageHelper<T> {
constructor(readonly key: string, private options: StorageHelperOptions<T>) {
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.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) {
this.init();
@ -126,6 +119,7 @@ export class StorageHelper<T> {
this.data.set(this.defaultValue);
}
@action
merge(value: Partial<T> | ((draft: Draft<T>) => Partial<T> | void)) {
const nextValue = produce(this.get(), (state: Draft<T>) => {
const newValue = isFunction(value) ? value(state) : value;