UNPKG

1.67 kBJavaScriptView Raw
1/**
2 * Persistence layer with expiration based on localStorage.
3 */
4
5class NamespacedLocalStorage {
6 constructor(localStorage, key) {
7 this.localStorage = localStorage;
8 this.key = key;
9 }
10 _makeKey(key) {
11 return `${this.key}__${key}`;
12 }
13 getItem(name) {
14 return this.localStorage.getItem(this._makeKey(name));
15 }
16 setItem(name, value) {
17 return this.localStorage.setItem(this._makeKey(name), value);
18 }
19 removeItem(name) {
20 return this.localStorage.removeItem(this._makeKey(name));
21 }
22}
23
24export default class BrowserPersistence {
25 static KEY = 'M2_VENIA_BROWSER_PERSISTENCE';
26 /* istanbul ignore next: test injects localstorage mock */
27 constructor(localStorage = window.localStorage) {
28 this.storage = new NamespacedLocalStorage(
29 localStorage,
30 this.constructor.KEY || BrowserPersistence.KEY
31 );
32 }
33 getItem(name) {
34 const now = Date.now();
35 const item = this.storage.getItem(name);
36 if (!item) {
37 return undefined;
38 }
39 const { value, ttl, timeStored } = JSON.parse(item);
40 if (ttl && now - timeStored > ttl * 1000) {
41 this.storage.removeItem(name);
42 return undefined;
43 }
44 return JSON.parse(value);
45 }
46 setItem(name, value, ttl) {
47 const timeStored = Date.now();
48 this.storage.setItem(
49 name,
50 JSON.stringify({
51 value: JSON.stringify(value),
52 timeStored,
53 ttl
54 })
55 );
56 }
57 removeItem(name) {
58 this.storage.removeItem(name);
59 }
60}