import { v4 as uuid } from 'uuid'; import once from 'lodash.once'; import { getDateString, getDifInMins } from './date.helper'; import { SESSION_CACHE_KEY, LAST_ACTIVITY_CACHE_KEY } from '../constants/constants'; type CachedSessionObj = { sessionId: string; sessionCreated: string; }; export const supportsSessionStorage = once(() => { const value = '_OMBORI_GRID_SIGNALS_SESSION_STORAGE_TEST'; try { sessionStorage.setItem(value, value); sessionStorage.removeItem(value); return true; } catch (e) { return false; } }); const getCachedSession = () => { try { const sessionStringCache = sessionStorage.getItem(SESSION_CACHE_KEY); if (!sessionStringCache) return null; return JSON.parse(sessionStringCache) as CachedSessionObj; } catch (e) { return null; } }; export const cacheSession = (sessionId: string, sessionCreated: string) => { sessionStorage.setItem(SESSION_CACHE_KEY, JSON.stringify({ sessionId, sessionCreated })); }; export const generateSession = ({ forceCreateNewSession = false, maxSessionLastActivityMins, }: { forceCreateNewSession?: boolean; maxSessionLastActivityMins: number; }) => { const sessionId = uuid(); const sessionCreated = getDateString(); if (supportsSessionStorage()) { const cachedSession = getCachedSession(); if ( !forceCreateNewSession && cachedSession && cachedSession.sessionId && cachedSession.sessionCreated ) { const lastActivity = getLastActivityCache(); if (lastActivity) { const isAfterMins = getDifInMins(getDateString(), lastActivity) >= maxSessionLastActivityMins; if (!isAfterMins) { return { sessionId: cachedSession.sessionId, sessionCreated: cachedSession.sessionCreated, isFromCache: true, }; } } } cacheSession(sessionId, sessionCreated); setLastActivityCache(sessionCreated); } return { sessionId, sessionCreated, isFromCache: false }; }; export const getLastActivityCache = () => { try { if (!supportsSessionStorage()) return null; const lastActivityCache = sessionStorage.getItem(LAST_ACTIVITY_CACHE_KEY); return lastActivityCache; } catch (e) { return null; } }; export const setLastActivityCache = (dateString: string) => { try { if (!supportsSessionStorage()) return false; sessionStorage.setItem(LAST_ACTIVITY_CACHE_KEY, dateString); return dateString; } catch (e) { return false; } };