local-storage.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * localStorage can throw browser exceptions, for example if it is full We don't
  3. * use localStorage for anything critical, so in that case just fail gracefully.
  4. */
  5. import { debugConsole } from '@/utils/debugging'
  6. /**
  7. * Catch, log and otherwise ignore errors.
  8. *
  9. * @param {function} fn localStorage function to call
  10. * @param {string?} key Key passed to the localStorage function (if any)
  11. * @param {any?} value Value passed to the localStorage function (if any)
  12. */
  13. const callSafe = function (
  14. fn: (...args: any) => any,
  15. key?: string,
  16. value?: any
  17. ) {
  18. try {
  19. return fn(key, value)
  20. } catch (e) {
  21. debugConsole.error('localStorage exception', e)
  22. return null
  23. }
  24. }
  25. const getItem = function (key: string) {
  26. const value = localStorage.getItem(key)
  27. return value === null ? null : JSON.parse(value)
  28. }
  29. const setItem = function (key: string, value: any) {
  30. localStorage.setItem(key, JSON.stringify(value))
  31. }
  32. const clear = function () {
  33. localStorage.clear()
  34. }
  35. const removeItem = function (key: string) {
  36. return localStorage.removeItem(key)
  37. }
  38. const customLocalStorage = {
  39. getItem: (key: string) => callSafe(getItem, key),
  40. setItem: (key: string, value: any) => callSafe(setItem, key, value),
  41. clear: () => callSafe(clear),
  42. removeItem: (key: string) => callSafe(removeItem, key),
  43. }
  44. export default customLocalStorage