Stop using @electron/remote to obtain app.getPath() (#4078)

* Stop using remote to obtain app.getPath()

- Initialize entire map in bootstrap()

- Updated unit tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Resolve PR comments

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix test

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix build

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Ensure that init can only be called once and catch errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Replace basically all uses of app.getPath() with AppPaths.get()

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix unit tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton authored and GitHub committed 2021-10-27 21:07:41 -04:00
1 parent 65b6908bf1
commit f297407156
45 files changed
+521 -200

No files matched your search

+27 -35
View File
@@ -26,7 +26,6 @@ import { comparer, observable, reaction, toJS, when } from "mobx";
import fse from "fs-extra";
import { StorageHelper } from "./storageHelper";
import logger from "../../main/logger";
import { getHostedClusterId, getPath } from "../../common/utils";
import { isTestEnv } from "../../common/vars";
const storage = observable({
@@ -37,55 +36,48 @@ const storage = observable({
/**
* Creates a helper for saving data under the "key" intended for window.localStorage
* @param key
* @param defaultValue
* @param key The descriptor of the data
* @param defaultValue The default value of the data, must be JSON serializable
*/
export function createStorage<T>(key: string, defaultValue: T) {
return createAppStorage(key, defaultValue, getHostedClusterId());
}
export function createAppStorage<T>(key: string, defaultValue: T, clusterId?: string | undefined) {
const { logPrefix } = StorageHelper;
const folder = path.resolve(getPath("userData"), "lens-local-storage");
const fileName = `${clusterId ?? "app"}.json`;
const filePath = path.resolve(folder, fileName);
if (!storage.initialized) {
init(); // called once per cluster-view
}
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(() => {
(async () => {
const filePath = await StorageHelper.getLocalStoragePath();
try {
storage.data = await fse.readJson(filePath);
} catch {} finally {
if (!isTestEnv) {
logger.info(`${logPrefix} loading finished for ${filePath}`);
}
storage.loaded = true;
}
// 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
});
// 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
});
async function saveFile(state: Record<string, any> = {}) {
logger.info(`${logPrefix} saving ${filePath}`);
async function saveFile(state: Record<string, any> = {}) {
logger.info(`${logPrefix} saving ${filePath}`);
try {
await fse.ensureDir(folder, { mode: 0o755 });
await fse.writeJson(filePath, state, { spaces: 2 });
} catch (error) {
logger.error(`${logPrefix} saving failed: ${error}`, {
json: state, jsonFilePath: filePath
});
try {
await fse.ensureDir(path.dirname(filePath), { mode: 0o755 });
await fse.writeJson(filePath, state, { spaces: 2 });
} catch (error) {
logger.error(`${logPrefix} saving failed: ${error}`, {
json: state, jsonFilePath: filePath
});
}
}
}
})()
.catch(error => logger.error(`${logPrefix} Failed to initialize storage: ${error}`));
}
return new StorageHelper<T>(key, {
+7
View File
@@ -24,6 +24,9 @@ import { action, comparer, makeObservable, observable, toJS, when, } from "mobx"
import produce, { Draft, isDraft } from "immer";
import { isEqual, isPlainObject } from "lodash";
import logger from "../../main/logger";
import { getHostedClusterId } from "../../common/utils";
import path from "path";
import { AppPaths } from "../../common/app-paths";
export interface StorageAdapter<T> {
[metadata: string]: any;
@@ -40,6 +43,10 @@ export interface StorageHelperOptions<T> {
}
export class StorageHelper<T> {
static async getLocalStoragePath() {
return path.resolve(await AppPaths.getAsync("userData"), "lens-local-storage", `${getHostedClusterId() || "app"}.json`);
}
static logPrefix = "[StorageHelper]:";
readonly storage: StorageAdapter<T>;