UNPKG

@darcas/keyplex

Version:

A versatile and modular library for managing namespaced key-value storage, with built-in support for localStorage and sessionStorage, and the ability to easily extend for custom storage solutions.

6 lines 1.27 kB
/** * @author Dario Casertano <dario@casertano.name> * @copyright Copyright (c) 2024-present Casertano Dario – All rights reserved. * @license MIT */ import forEach from"lodash/forEach";import{default as lodashKeys}from"lodash/keys";export class KeyPlex{constructor(e){this.dbname=e||new URL(location.href).hostname.split(".").reverse().join(".")}get(e,t=null){const s=this.getItem(this.getPath(e));return s?JSON.parse(s):t}set(e,t){this.setItem(this.getPath(e),JSON.stringify(t))}del(e){const t=this.getPath(e);if(t.endsWith("%")){const e=t.substring(0,t.length-1);forEach(this.keys(),(t=>{t.startsWith(e)&&this.removeItem(t)}))}else this.removeItem(this.getPath(e))}has(e){return null!==this.get(e)}getPath(e){return[`@${this.dbname}`,e].join("/")}}export class LocalPlex extends KeyPlex{constructor(){super(...arguments),this.keys=()=>lodashKeys(localStorage),this.getItem=e=>localStorage.getItem(e),this.setItem=(e,t)=>localStorage.setItem(e,t),this.removeItem=e=>localStorage.removeItem(e)}}export class SessionPlex extends KeyPlex{constructor(){super(...arguments),this.keys=()=>lodashKeys(sessionStorage),this.getItem=e=>sessionStorage.getItem(e),this.setItem=(e,t)=>sessionStorage.setItem(e,t),this.removeItem=e=>sessionStorage.removeItem(e)}}