UNPKG

loco-cache

Version:

cache data using browser session storage

133 lines (114 loc) 3.28 kB
"use strict"; function e() { throw new Error("loco-cache should be instantiated before use. e.g.\nconst loco = require('loco-cache')()"); } function t(e) { for (var t = 1; t < arguments.length; t++) { var r = arguments[t]; if (r == null) continue; for (var i in r) { e[i] = r[i]; } } return e; } function r(e, t) { return e.substr(0, t.length) === t; } function i(e) { if (this == null) return new i(e); this.options = t({ prefix: "loco", expiresIn: 600, compression: null, storage: "session" }, e); this.timer = null; this.timeoutLeft = 0; } i.prototype.getStorage = function() { switch (this.options.storage) { case "session": return window.sessionStorage; case "local": return window.localStorage; default: return undefined; } }; i.prototype.sweep = function(e) { e = t({}, this.options, e); var i = this.getStorage(); if (i == undefined) return undefined; var n = e.prefix + "-meta-"; var o = new Date().getTime(); for (var s in i) { if (!r(s, n)) continue; var u = s; var a = i.getItem(u); if (a != null) { var f = JSON.parse(a); if (f.expiration >= o) continue; } var p = e.prefix + "-data-" + s.substring(n.length); i.removeItem(u); i.removeItem(p); } }; i.prototype.refreshTimer = function() { var e = this; e.timeoutLeft = 20; function t() { e.timer = null; if (e.timeoutLeft <= 0) return; e.timeoutLeft -= 1; e.sweep(); e.timer = setTimeout(t, 5e3); } if (this.timer == null) this.timer = setTimeout(t, 5e3); }; i.prototype.setStr = function(e, r, i) { if (e == null || typeof e !== "string") throw new Error("key has to be a string"); if (r == null || typeof r !== "string") throw new Error("valstr has to be a string"); i = t({}, this.options, i); var n = this.getStorage(); if (n == undefined) return this; this.refreshTimer(); r = i.compression ? i.compression.compress(r) : r; var o = new Date().getTime() + i.expiresIn * 1e3; var s = JSON.stringify({ expiration: o }); n.setItem(i.prefix + "-data-" + e, r); n.setItem(i.prefix + "-meta-" + e, s); return this; }; i.prototype.getStr = function(e, r) { if (e == null || typeof e !== "string") throw new Error("key has to be a string"); r = t({}, this.options, r); var i = this.getStorage(); if (i == undefined) return undefined; this.refreshTimer(); var n = new Date().getTime(); var o = i.getItem(r.prefix + "-meta-" + e); if (o == null) return undefined; var s = JSON.parse(o); if (s.expiration < n) return undefined; var u = i.getItem(r.prefix + "-data-" + e); u = r.compression ? r.compression.decompress(u) : u; return u; }; i.prototype.set = function(e, t, r) { return this.setStr(e, JSON.stringify(t), r); }; i.prototype.get = function(e, t) { var r = this.getStr(e, t); if (r == undefined) return undefined; return JSON.parse(r); }; i.sweep = e; i.setStr = e; i.getStr = e; i.set = e; i.get = e; module.exports = i;