UNPKG

ionstore

Version:

A very simple isomorphic key-value store with a Map-like API for persisting session data.

59 lines (58 loc) 2.54 kB
/* IMPORT */ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _AbstractStore_save; import { attempt } from './utils.js'; /* MAIN */ class AbstractStore extends Map { /* CONSTRUCTOR */ constructor(options) { super(); /* VARIABLES */ _AbstractStore_save.set(this, void 0); const { id, backend } = options; if (!/^[a-zA-Z0-9_-]+$/.test(id)) throw new Error(`Invalid store id: "${id}"`); const read = () => attempt(() => backend.read(id), []); const write = () => attempt(() => backend.write(id, this.entries()), null); for (const [key, value] of read()) { super.set(key, value); } __classPrivateFieldSet(this, _AbstractStore_save, write, "f"); return this; } /* API */ clear() { if (!this.size) return; super.clear(); __classPrivateFieldGet(this, _AbstractStore_save, "f").call(this); } delete(key) { const deleted = super.delete(key); if (!deleted) return false; __classPrivateFieldGet(this, _AbstractStore_save, "f").call(this); return true; } set(key, value) { const valuePrev = this.get(key); if (value === valuePrev) return this; super.set(key, value); __classPrivateFieldGet(this, _AbstractStore_save, "f").call(this); return this; } } _AbstractStore_save = new WeakMap(); /* EXPORT */ export default AbstractStore;