UNPKG

@vegajs/storage

Version:

A flexible and type-safe storage service adapter for TypeScript and JavaScript. Supports various storage mechanisms like localStorage, query strings, and mock storage with both asynchronous and synchronous APIs.

1 lines 873 B
import{isJsonString as t}from"@vegajs/shared";const e=new Error("localStorage is not supported");class r{constructor(){this.storage="undefined"!==typeof window?window?.localStorage:void 0}assertStorageAvailable(){if(!this.storage)throw e}clearItem(t){this.assertStorageAvailable(),this.storage.removeItem(t)}clear(){this.assertStorageAvailable(),this.storage.clear()}getItem(t){return new Promise((e=>e(this.getItemSync(t))))}getItemSync(e){this.assertStorageAvailable();const r=this.storage.getItem(e);if(!r)return null;try{return t(r)?JSON.parse(r):r}catch(s){return null}}setItem(t,e){return new Promise((r=>r(this.setItemSync(t,e))))}setItemSync(t,e){this.assertStorageAvailable();let r=e;"string"!==typeof e&&(r=JSON.stringify(r)),this.storage.setItem(t,r)}has(t){return this.assertStorageAvailable(),Boolean(this.storage.getItem(t))}}export{r as LocalStorageAdapter};