Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // session-cache.js
- 'use strict';
- const createSessionCache = () => {
- const cache = new Map();
- const updateLocalStorage = () => {
- try {
- const cacheData = JSON.stringify(Array.from(cache.entries()));
- localStorage.setItem('cache', cacheData);
- } catch (error) {
- console.error('Failed to update cache in localStorage:', error);
- }
- };
- const initializeCacheFromLocalStorage = () => {
- try {
- const cacheData = localStorage.getItem('cache');
- if (cacheData) {
- const entries = JSON.parse(cacheData);
- entries.forEach(([key, value]) => {
- cache.set(key, value);
- });
- }
- } catch (error) {
- console.error('Failed to initialize cache from localStorage:', error);
- }
- };
- const setCache = (key, value) => {
- cache.set(key, value);
- updateLocalStorage();
- };
- const getCache = (key) => cache.get(key);
- const removeCache = (key) => {
- cache.delete(key);
- updateLocalStorage();
- };
- const clearCache = () => {
- cache.clear();
- updateLocalStorage();
- };
- const setCacheWithExpiry = (key, value, ttl) => {
- const now = new Date();
- const item = {
- value,
- expiry: now.getTime() + ttl,
- };
- setCache(key, item);
- };
- const getCacheWithExpiry = (key) => {
- const item = cache.get(key);
- if (!item) {
- return null;
- }
- const now = new Date();
- if (now.getTime() > item.expiry) {
- removeCache(key);
- return null;
- }
- return item.value;
- };
- initializeCacheFromLocalStorage();
- return {
- setCache,
- getCache,
- removeCache,
- clearCache,
- setCacheWithExpiry,
- getCacheWithExpiry,
- };
- };
- export default createSessionCache;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement