UNPKG

@gleaner/tracker

Version:

A JavaScript tracking library with ecommerce support

88 lines (75 loc) 1.57 kB
import { hasLocalStorage } from './utils' const HAS_LOCAL_STORAGE = hasLocalStorage() /* A wrapper over localStorage, which prefixes all items with a cache name */ class Cache { /* @param {String} */ constructor(name) { this.name = name; this.keys = {}; this.keyName = this.name + "keys"; if (HAS_LOCAL_STORAGE) { // attempt to continue where left off... this._loadKeys(); } } /* @param {String} @param {Object} */ add(key, value) { if (HAS_LOCAL_STORAGE) { const keyName = this.name + key; this.keys[keyName] = true; this._storeKeys(); localStorage.setItem(keyName, JSON.stringify(value)); } } /* @param {String} */ delete(key) { if (HAS_LOCAL_STORAGE) { const keyName = this.name + key; delete this.keys[keyName]; this._storeKeys(); // when removed last one, could also remove the keys map... localStorage.removeItem(keyName); } } /* @returns {Array} */ getAll() { let events = []; if (HAS_LOCAL_STORAGE) { events = this._keysAsArray().map((key) => JSON.parse(localStorage.getItem(key))); } return events; } deleteAll() { for (let key in this.keys) localStorage.removeItem(key); this.keys = {}; localStorage.removeItem(this.keyName); } /* @returns {Array} */ _keysAsArray() { let keys = []; for (let key in this.keys) keys.push(key); return keys; } _storeKeys() { localStorage.setItem(this.keyName, JSON.stringify(this.keys)); } _loadKeys() { this.keys = JSON.parse(localStorage.getItem(this.keyName)) || {}; } } export default Cache;