From a3658de7c2c579a38ee1dde921a8fdec285a6608 Mon Sep 17 00:00:00 2001 From: yuhui1208 <51014425+yuhui1208@users.noreply.github.com> Date: Thu, 2 Jul 2020 17:44:04 +0800 Subject: [PATCH] [Stores] make FileStroe read key safely (#338) * safely readKey * fix ci * fix * fix type error * Modify judgment * fix * fix * fix lint --- packages/ui-keyring/src/stores/File.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/packages/ui-keyring/src/stores/File.ts b/packages/ui-keyring/src/stores/File.ts index 98eb18a7..29042b53 100644 --- a/packages/ui-keyring/src/stores/File.ts +++ b/packages/ui-keyring/src/stores/File.ts @@ -25,12 +25,20 @@ export default class FileStore implements KeyringStore { .readdirSync(this.#path) .filter((key): boolean => !['.', '..', '.DS_Store'].includes(key)) .forEach((key): void => { - cb(key, this._readKey(key)); + const value = this._readKey(key); + + if (JSON.stringify(value) !== '{}') { + cb(key, value); + } }); } public get (key: string, cb: (value: KeyringJson) => void): void { - cb(this._readKey(key)); + const value = this._readKey(key); + + if (JSON.stringify(value) !== '{}') { + cb(value); + } } public remove (key: string, cb?: () => void): void { @@ -48,8 +56,14 @@ export default class FileStore implements KeyringStore { } private _readKey (key: string): KeyringJson { - return JSON.parse( - fs.readFileSync(this._getPath(key)).toString('utf-8') - ) as KeyringJson; + try { + return JSON.parse( + fs.readFileSync(this._getPath(key)).toString('utf-8') + ) as KeyringJson; + } catch (error) { + console.log('_readKey error:', error); + + return {} as KeyringJson; + } } }