smhdale

Schema-based persistent key-value meta storage

Feb 21st, 2021 (edited)
284
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @file Manages metadata and persists it to LocalStorage.
  3.  */
  4.  
  5. type LocalMetaSchema = {
  6.     muted: boolean
  7. };
  8.  
  9. type LocalMetaKey = keyof LocalMetaSchema;
  10.  
  11. class LocalMeta {
  12.     private _key: string;
  13.     private _mem: Record<string, any> = {}
  14.  
  15.     constructor(storageKey: string, initialState: LocalMetaSchema) {
  16.         this._key = storageKey;
  17.  
  18.         try {
  19.             // Attempt to load meta from disk.
  20.             const raw = localStorage.getItem(this._key);
  21.             if (raw === null) throw Error();
  22.             this._mem = JSON.parse(raw);
  23.         } catch {
  24.             // Remove (possibly corrupt) saved meta.
  25.             console.log('Failed to load meta from LocalStorage.');
  26.             localStorage.removeItem(this._key);
  27.  
  28.             // Set from initial state.
  29.             this._mem = initialState;
  30.             this._persist();
  31.         }
  32.     }
  33.  
  34.     // Persists in-memory meta to disk.
  35.     private _persist() {
  36.         localStorage.setItem(this._key, JSON.stringify(this._mem));
  37.     }
  38.  
  39.     // Sets a meta value.
  40.     public set<K extends LocalMetaKey, V extends LocalMetaSchema[K]>(key: K, value: V) {
  41.         // Save in memory and on disk.
  42.         this._mem[key] = value;
  43.         this._persist();
  44.     }
  45.  
  46.     // Gets a meta value.
  47.     public get<K extends LocalMetaKey, V extends LocalMetaSchema[K]>(key: K): V {
  48.         return this._mem[key];
  49.     }
  50. }
  51.  
  52. // Export singleton.
  53. const metaKey = process.env.LOCAL_STORAGE_KEY || 'meta';
  54. const initialState: LocalMetaSchema = {
  55.     muted: false,
  56. };
  57. export default new LocalMeta(metaKey, initialState);
Add Comment
Please, Sign In to add comment