import once from 'lodash.once'; import { DataRequestTypeEnum, SendOrCacheDataProps, RequestData } from '../types/signal.types'; import { EVENTS_CACHE_KEY } from '../constants/constants'; export const supportsLocalStorage = once(() => { const value = '_OMBORI_GRID_SIGNALS_CACHE_TEST'; try { localStorage.setItem(value, value); localStorage.removeItem(value); return true; } catch (e) { return false; } }); export const cache: any[] = supportsLocalStorage() ? JSON.parse(localStorage.getItem(EVENTS_CACHE_KEY) || '[]') : []; export const cacheData = (type: DataRequestTypeEnum, data: RequestData) => { // If the device is offline for a long time we don't want the cache to grow infinitely if (cache.length >= 10000) { cache.shift(); } cache.push({ type, data }); supportsLocalStorage() && localStorage.setItem(EVENTS_CACHE_KEY, JSON.stringify(cache)); }; const delay = (ms: number) => new Promise(resolve => { setTimeout(resolve, ms); }); const flushCache = async (sendOrCacheData: SendOrCacheDataProps) => { while (cache.length) { const event = cache.shift(); if (event) { sendOrCacheData(event.type, event.data); // Don't flush the cache too quickly as it can lead to dropped events await delay(100); } } supportsLocalStorage() && localStorage.removeItem(EVENTS_CACHE_KEY); flushCacheOnce = once(flushCache); }; export let flushCacheOnce = once(flushCache);