@georapbox/web-storage
Version:
WebStorage is a lightweight wrapper for namespaced localStorage/sessionStorage with support for serializable values and safe, tuple-based error handling.
12 lines (11 loc) • 2.67 kB
JavaScript
/*!
* @georapbox/web-storage
* WebStorage is a lightweight wrapper for namespaced localStorage/sessionStorage with support for serializable values and safe, tuple-based error handling.
*
* @version 3.0.0
* @homepage https://github.com/georapbox/web-storage#readme
* @author George Raptis <georapbox@gmail.com>
* @license MIT
*/
var u="localStorage",c="web-storage/",l="__web-storage-test__";function s(o,r){return o.startsWith(r)?o.slice(r.length):o}var i=class o{#r;#t="";constructor(r={}){let e={...{driver:u,keyPrefix:c},...r};if(e.driver!=="localStorage"&&e.driver!=="sessionStorage")throw new Error('The "driver" option must be one of "localStorage" or "sessionStorage".');if(typeof e.keyPrefix!="string")throw new TypeError('The "keyPrefix" option must be a string.');this.#r=window[e.driver],this.#t=e.keyPrefix.trim()}static isAvailable(r){try{let t=window[r],e=l;return t.setItem(e,"test"),t.getItem(e),t.removeItem(e),!0}catch{return!1}}static createInstance(r){return new o(r)}setItem(r,t){if(typeof r!="string")throw new TypeError("Failed to execute 'setItem' on 'Storage': The first argument must be a string.");try{let e=this.#t+r,n=t==null||typeof t=="function"?null:t;return this.#r.setItem(e,JSON.stringify(n)),[!0,null]}catch(e){return[!1,e instanceof Error?e:new Error(String(e))]}}getItem(r){if(typeof r!="string")throw new TypeError("Failed to execute 'getItem' on 'Storage': The first argument must be a string.");try{let t=this.#r.getItem(this.#t+r);return t===null?[null,null]:[JSON.parse(t),null]}catch(t){return[null,t instanceof Error?t:new Error(String(t))]}}removeItem(r){if(typeof r!="string")throw new TypeError("Failed to execute 'removeItem' on 'Storage': The first argument must be a string.");try{return this.#r.removeItem(this.#t+r),[!0,null]}catch(t){return[!1,t instanceof Error?t:new Error(String(t))]}}clear(){try{return this.#e(r=>this.#r.removeItem(r)),[!0,null]}catch(r){return[!1,r instanceof Error?r:new Error(String(r))]}}keys(){try{let r=[];return this.#e(t=>{let e=s(t,this.#t);r.push(e)}),[r,null]}catch(r){return[[],r instanceof Error?r:new Error(String(r))]}}length(){let[r,t]=this.keys();return!Array.isArray(r)||t?[0,t]:[r.length,null]}iterate(r){if(typeof r!="function")throw new TypeError("Failed to iterate on 'Storage': 'iteratorCallback' must be a function.");try{return this.#e((t,e)=>{let n=s(t,this.#t),a=e===null?null:JSON.parse(e);r(a,n)}),[!0,null]}catch(t){return[!1,t instanceof Error?t:new Error(String(t))]}}#e(r){let t=Object.keys(this.#r);for(let e=0;e<t.length;e++){let n=t[e];n.startsWith(this.#t)&&r(n,this.#r.getItem(n))}}};export{i as WebStorage};
//# sourceMappingURL=web-storage.js.map