Introduce store helper

Responsible for serializing/deserializing data to be saved in
localStorage. Add a prefix to all localStorage entries to avoid
conflicts with other webapps. Stop guarding against localStorage
not existing, browsers can just implement a dumb interface to
disable it.
This commit is contained in:
Simon Ser 2021-05-26 18:43:11 +02:00
parent 12a38ace90
commit 695b02caaa
4 changed files with 62 additions and 33 deletions

46
store.js Normal file
View file

@ -0,0 +1,46 @@
const PREFIX = "gamja_";
function getItem(k) {
k = PREFIX + k;
}
function setItem(k, v) {
k = PREFIX + k;
}
class Item {
constructor(k) {
this.k = PREFIX + k;
}
load() {
var v = localStorage.getItem(this.k);
if (!v) {
return null;
}
return JSON.parse(v);
}
put(v) {
if (v) {
localStorage.setItem(this.k, JSON.stringify(v));
} else {
localStorage.removeItem(this.k);
}
}
}
export const autoconnect = new Item("autoconnect");
const rawReceipts = new Item("receipts");
export const receipts = {
load() {
var v = rawReceipts.load();
return new Map(Object.entries(v || {}));
},
put(m) {
rawReceipts.put(Object.fromEntries(m));
},
};