Advertisement
okpalan

session-cache.js

Nov 9th, 2023
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // session-cache.js
  2.  
  3. 'use strict';
  4.  
  5. const createSessionCache = () => {
  6.   const cache = new Map();
  7.  
  8.   const updateLocalStorage = () => {
  9.     try {
  10.       const cacheData = JSON.stringify(Array.from(cache.entries()));
  11.       localStorage.setItem('cache', cacheData);
  12.     } catch (error) {
  13.       console.error('Failed to update cache in localStorage:', error);
  14.     }
  15.   };
  16.  
  17.   const initializeCacheFromLocalStorage = () => {
  18.     try {
  19.       const cacheData = localStorage.getItem('cache');
  20.       if (cacheData) {
  21.         const entries = JSON.parse(cacheData);
  22.         entries.forEach(([key, value]) => {
  23.           cache.set(key, value);
  24.         });
  25.       }
  26.     } catch (error) {
  27.       console.error('Failed to initialize cache from localStorage:', error);
  28.     }
  29.   };
  30.  
  31.   const setCache = (key, value) => {
  32.     cache.set(key, value);
  33.     updateLocalStorage();
  34.   };
  35.  
  36.   const getCache = (key) => cache.get(key);
  37.  
  38.   const removeCache = (key) => {
  39.     cache.delete(key);
  40.     updateLocalStorage();
  41.   };
  42.  
  43.   const clearCache = () => {
  44.     cache.clear();
  45.     updateLocalStorage();
  46.   };
  47.  
  48.   const setCacheWithExpiry = (key, value, ttl) => {
  49.     const now = new Date();
  50.     const item = {
  51.       value,
  52.       expiry: now.getTime() + ttl,
  53.     };
  54.  
  55.     setCache(key, item);
  56.   };
  57.  
  58.   const getCacheWithExpiry = (key) => {
  59.     const item = cache.get(key);
  60.     if (!item) {
  61.       return null;
  62.     }
  63.  
  64.     const now = new Date();
  65.  
  66.     if (now.getTime() > item.expiry) {
  67.       removeCache(key);
  68.       return null;
  69.     }
  70.  
  71.     return item.value;
  72.   };
  73.  
  74.   initializeCacheFromLocalStorage();
  75.  
  76.   return {
  77.     setCache,
  78.     getCache,
  79.     removeCache,
  80.     clearCache,
  81.     setCacheWithExpiry,
  82.     getCacheWithExpiry,
  83.   };
  84. };
  85.  
  86. export default createSessionCache;
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement