import Cookies from 'js-cookie'; export default class DataStorage { static storageMethod = process.env.REACT_APP_STORAGE_METHOD; // Get data static get(key) { if (this.storageMethod === 'session') { return sessionStorage.getItem(key); } else if (this.storageMethod === 'cookie') { return Cookies.get(key); } return null; } // Set data static set(key, value, param = { expiryDate: null }) { if (this.storageMethod === 'session') { sessionStorage.setItem(key, value); } else if (this.storageMethod === 'cookie') { if (param.expiryDate) { const expiryDate = new Date(param.expiryDate * 1000); Cookies.set(key, value, { expires: expiryDate }) } else if (Cookies.get('expiryDate')) { const expiryDate = new Date(Cookies.get('expiryDate') * 1000); Cookies.set(key, value, { expires: expiryDate }); } else Cookies.set(key, value, { expires: 7 })// Expires in 7 by default } } // Remove data static remove(key) { if (this.storageMethod === 'session') { sessionStorage.removeItem(key); } else if (this.storageMethod === 'cookie') { Cookies.remove(key); } } // Get all data static getAll() { const data = {}; if (this.storageMethod === 'session') { for (let i = 0; i < sessionStorage.length; i++) { const key = sessionStorage.key(i); data[key] = sessionStorage.getItem(key); } } else if (this.storageMethod === 'cookie') { const cookies = Cookies.get(); Object.keys(cookies).forEach(key => { data[key] = cookies[key]; }); } return data; } // Clear all data static clearAll() { if (this.storageMethod === 'session') { sessionStorage.clear(); } else if (this.storageMethod === 'cookie') { const cookies = Cookies.get(); Object.keys(cookies).forEach(key => { Cookies.remove(key); }); } } // Check if a key exists static hasKey(key) { if (this.storageMethod === 'session') { return sessionStorage.getItem(key) !== null; } else if (this.storageMethod === 'cookie') { return Cookies.get(key) !== undefined; } return false; } // Get all keys static getKeys() { const keys = []; if (this.storageMethod === 'session') { for (let i = 0; i < sessionStorage.length; i++) { keys.push(sessionStorage.key(i)); } } else if (this.storageMethod === 'cookie') { keys.push(...Object.keys(Cookies.get())); } return keys; } }