store.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. type StoreValue = string | number | boolean | null;
  2. export class Store {
  3. get(key: string) {
  4. return window.localStorage[key];
  5. }
  6. set(key: string, value: StoreValue) {
  7. window.localStorage[key] = value;
  8. }
  9. getBool(key: string, def: boolean): boolean {
  10. if (def !== void 0 && !this.exists(key)) {
  11. return def;
  12. }
  13. return window.localStorage[key] === 'true';
  14. }
  15. getObject<T = unknown>(key: string): T | undefined;
  16. getObject<T = unknown>(key: string, def: T): T;
  17. getObject<T = unknown>(key: string, def?: T) {
  18. let ret = def;
  19. if (this.exists(key)) {
  20. const json = window.localStorage[key];
  21. try {
  22. ret = JSON.parse(json);
  23. } catch (error) {
  24. console.error(`Error parsing store object: ${key}. Returning default: ${def}. [${error}]`);
  25. }
  26. }
  27. return ret;
  28. }
  29. /* Returns true when successfully stored, throws error if not successfully stored */
  30. setObject(key: string, value: any) {
  31. let json;
  32. try {
  33. json = JSON.stringify(value);
  34. } catch (error) {
  35. throw new Error(`Could not stringify object: ${key}. [${error}]`);
  36. }
  37. try {
  38. this.set(key, json);
  39. } catch (error) {
  40. // Likely hitting storage quota
  41. const errorToThrow = new Error(`Could not save item in localStorage: ${key}. [${error}]`);
  42. errorToThrow.name = error.name;
  43. throw errorToThrow;
  44. }
  45. return true;
  46. }
  47. exists(key: string) {
  48. return window.localStorage[key] !== void 0;
  49. }
  50. delete(key: string) {
  51. window.localStorage.removeItem(key);
  52. }
  53. }
  54. const store = new Store();
  55. export default store;