Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @file Manages metadata and persists it to LocalStorage.
- */
- type LocalMetaSchema = {
- muted: boolean
- };
- type LocalMetaKey = keyof LocalMetaSchema;
- class LocalMeta {
- private _key: string;
- private _mem: Record<string, any> = {}
- constructor(storageKey: string, initialState: LocalMetaSchema) {
- this._key = storageKey;
- try {
- // Attempt to load meta from disk.
- const raw = localStorage.getItem(this._key);
- if (raw === null) throw Error();
- this._mem = JSON.parse(raw);
- } catch {
- // Remove (possibly corrupt) saved meta.
- console.log('Failed to load meta from LocalStorage.');
- localStorage.removeItem(this._key);
- // Set from initial state.
- this._mem = initialState;
- this._persist();
- }
- }
- // Persists in-memory meta to disk.
- private _persist() {
- localStorage.setItem(this._key, JSON.stringify(this._mem));
- }
- // Sets a meta value.
- public set<K extends LocalMetaKey, V extends LocalMetaSchema[K]>(key: K, value: V) {
- // Save in memory and on disk.
- this._mem[key] = value;
- this._persist();
- }
- // Gets a meta value.
- public get<K extends LocalMetaKey, V extends LocalMetaSchema[K]>(key: K): V {
- return this._mem[key];
- }
- }
- // Export singleton.
- const metaKey = process.env.LOCAL_STORAGE_KEY || 'meta';
- const initialState: LocalMetaSchema = {
- muted: false,
- };
- export default new LocalMeta(metaKey, initialState);
Add Comment
Please, Sign In to add comment