From 9a17097543c660763f7085ea3c103c6e650c0e94 Mon Sep 17 00:00:00 2001 From: Sebastian Malton Date: Wed, 27 Oct 2021 09:08:24 -0400 Subject: [PATCH] Ensure that init can only be called once and catch errors Signed-off-by: Sebastian Malton --- src/renderer/utils/createStorage.ts | 60 ++++++++++++++--------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/src/renderer/utils/createStorage.ts b/src/renderer/utils/createStorage.ts index cb4c48f825..c717784ecf 100755 --- a/src/renderer/utils/createStorage.ts +++ b/src/renderer/utils/createStorage.ts @@ -44,40 +44,40 @@ export function createStorage(key: string, defaultValue: T) { if (!storage.initialized) { storage.initialized = true; - init(); // called once per cluster-view - } - async function init() { - 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 - }); - - async function saveFile(state: Record = {}) { - logger.info(`${logPrefix} saving ${filePath}`); + (async () => { + const filePath = await StorageHelper.getLocalStoragePath(); 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 - }); + 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 + }); + + async function saveFile(state: Record = {}) { + logger.info(`${logPrefix} saving ${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(key, {