UNPKG

browser-cache-async

Version:

The browser-cache-async package provides a highly customizable, asynchronous caching system for client-side data management. Leveraging the power of the browser's IndexedDB, it enables efficient storage and retrieval of API responses, significantly reduci

1 lines 1.2 kB
import{IndexedDBStore}from"browser-keyval-stores";import{buildQueryOptions,canQueryBeCached,unwrapData,wrapData}from"./utils/index.js";class BrowserCache{__store;__debugMode;constructor(e,t=!1){this.__store=new IndexedDBStore(e),this.__debugMode=t}async __get(e){try{return unwrapData(await this.__store.get(e))}catch(t){return void(this.__debugMode&&console.error(`${this.__store.id}.__get(${e}) ->`,t))}}async __set(e,t,s){try{await this.__store.set(e,wrapData(t,s))}catch(t){this.__debugMode&&console.error(`${this.__store.id}.__set(${e}, ...) ->`,t)}}async run(e){const{id:t,query:s,cacheIf:r,revalidate:o}=buildQueryOptions(e),_=await this.__get(t);if(_)return this.__debugMode&&console.log(`${this.__store.id} -> CACHE_HIT: ${t}`,_),_;this.__debugMode&&console.log(`${this.__store.id} -> CACHE_MISS: ${t}`);const i=await s();return await canQueryBeCached(t,i,r)?(await this.__set(t,i,o),this.__debugMode&&console.log(`${this.__store.id} -> CACHE_SET: ${t}`,i)):this.__debugMode&&console.log(`${this.__store.id} -> CACHE_SKIP: ${t}`,i),i}async revalidate(e){try{await this.__store.del(e)}catch(t){this.__debugMode&&console.error(`${this.__store.id}.revalidate(${e}) ->`,t)}}}export{BrowserCache};