2020-09-18 10:04:31 +00:00
|
|
|
/**
|
|
|
|
* localStorage can throw browser exceptions, for example if it is full We don't
|
|
|
|
* use localStorage for anything critical, so in that case just fail gracefully.
|
|
|
|
*/
|
|
|
|
|
2023-09-27 09:45:49 +00:00
|
|
|
import { debugConsole } from '@/utils/debugging'
|
|
|
|
|
2020-09-18 10:04:31 +00:00
|
|
|
/**
|
|
|
|
* Catch, log and otherwise ignore errors.
|
|
|
|
*
|
|
|
|
* @param {function} fn localStorage function to call
|
|
|
|
* @param {string?} key Key passed to the localStorage function (if any)
|
|
|
|
* @param {any?} value Value passed to the localStorage function (if any)
|
|
|
|
*/
|
2021-04-14 13:17:21 +00:00
|
|
|
const callSafe = function (fn, key, value) {
|
2020-09-18 10:04:31 +00:00
|
|
|
try {
|
|
|
|
return fn(key, value)
|
|
|
|
} catch (e) {
|
2023-09-27 09:45:49 +00:00
|
|
|
debugConsole.error('localStorage exception', e)
|
2020-09-18 10:04:31 +00:00
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-14 13:17:21 +00:00
|
|
|
const getItem = function (key) {
|
2020-09-18 10:04:31 +00:00
|
|
|
return JSON.parse(localStorage.getItem(key))
|
|
|
|
}
|
|
|
|
|
2021-04-14 13:17:21 +00:00
|
|
|
const setItem = function (key, value) {
|
2020-09-18 10:04:31 +00:00
|
|
|
localStorage.setItem(key, JSON.stringify(value))
|
|
|
|
}
|
|
|
|
|
2021-04-14 13:17:21 +00:00
|
|
|
const clear = function () {
|
2020-09-18 10:04:31 +00:00
|
|
|
localStorage.clear()
|
|
|
|
}
|
|
|
|
|
2021-04-14 13:17:21 +00:00
|
|
|
const removeItem = function (key) {
|
2020-09-18 10:04:31 +00:00
|
|
|
return localStorage.removeItem(key)
|
|
|
|
}
|
|
|
|
|
|
|
|
const customLocalStorage = {
|
|
|
|
getItem: key => callSafe(getItem, key),
|
|
|
|
setItem: (key, value) => callSafe(setItem, key, value),
|
|
|
|
clear: () => callSafe(clear),
|
2021-04-27 07:52:58 +00:00
|
|
|
removeItem: key => callSafe(removeItem, key),
|
2020-09-18 10:04:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export default customLocalStorage
|