const useStorage = ($storage) => {
const get = (key: string) => {
let value = $storage.getItem(key);
try {
value = JSON.parse(value);
return value;
} catch {
return value;
}
}
const set = (key: string, value: any) => {
try {
return $storage.setItem(key, value ? JSON.stringify(value) : value);
} catch (error) {
const errorInfo = JSON.stringify(error).toUpperCase()
const isMatch = errorInfo.indexOf(key) !== -1
if (errorInfo.indexOf('QUOTA') !== -1) {
if (isMatch && isArray(value) && value.length ) {
return $storage.setItem(key, value ? JSON.stringify(value.slice(-200)) : value);
}
throw new Error(error);
}
throw new Error(error);
}
}
const remove = (key: string) => {
return $storage.removeItem(key);
}
const clearExcept = (key: string) => {
for (let i = 0; i < $storage.length; i++) {
const itemKey: string | undefined = $storage.key(i);
if (itemKey && itemKey !== key) {
$storage.removeItem(itemKey);
}
}
}
const clearAll = () => {
for (const itemKey in $storage) {
if (itemKey) {
$storage.removeItem(itemKey);
}
}
}
return {
get,
set,
remove,
clearExcept,
clearAll,
}
}
const SessionStorageService = useStorage(window.sessionStorage || sessionStorage)
const LocalStorageService = useStorage(window.localStorage || localStorage)
export {
SessionStorageService,
LocalStorageService,
}