@electerm/electerm-react 5.1.6 → 5.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client/common/cache.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// we persist cache to local storage, so we can keep cache after restart
|
|
4
4
|
|
|
5
5
|
import { safeGetItem, safeSetItem } from './safe-local-storage.js'
|
|
6
|
+
import safeParse from './parse-json-safe.js'
|
|
6
7
|
|
|
7
8
|
class MapCache {
|
|
8
9
|
constructor (limit, key) {
|
|
@@ -15,7 +16,7 @@ class MapCache {
|
|
|
15
16
|
load () {
|
|
16
17
|
const data = safeGetItem(this.key)
|
|
17
18
|
if (data) {
|
|
18
|
-
const arr =
|
|
19
|
+
const arr = safeParse(data, [])
|
|
19
20
|
for (const item of arr) {
|
|
20
21
|
this.cache.set(item.key, item.value)
|
|
21
22
|
}
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* safe parse json
|
|
3
|
+
* @param {string} str
|
|
4
|
+
* @param defaultValue value returned when parse fails or str is empty/null.
|
|
5
|
+
* Falls back to the original str when not provided.
|
|
3
6
|
*/
|
|
4
|
-
export default str => {
|
|
7
|
+
export default (str, defaultValue) => {
|
|
8
|
+
const hasDefault = defaultValue !== undefined
|
|
5
9
|
if (str === '' || str == null) {
|
|
6
|
-
return str
|
|
10
|
+
return hasDefault ? defaultValue : str
|
|
7
11
|
}
|
|
8
12
|
try {
|
|
9
13
|
return JSON.parse(str)
|
|
10
14
|
} catch (e) {
|
|
11
15
|
console.error('JSON.parse fails', e.stack)
|
|
12
|
-
return str
|
|
16
|
+
return hasDefault ? defaultValue : str
|
|
13
17
|
}
|
|
14
18
|
}
|