113 lines
2.7 KiB
TypeScript
113 lines
2.7 KiB
TypeScript
import { Security } from "@/lib/security";
|
|
import { clientEnv } from "@/lib/env.client";
|
|
|
|
type StorageValue = any;
|
|
|
|
const parseStoredValue = (value: string): StorageValue => {
|
|
if (!value || value.trim() === "") {
|
|
return null;
|
|
}
|
|
|
|
if (clientEnv.ENV !== "prod") {
|
|
return JSON.parse(value);
|
|
}
|
|
|
|
const decryptValue = Security.decryptBase64(value);
|
|
if (!decryptValue || decryptValue.trim() === "") {
|
|
return null;
|
|
}
|
|
|
|
return JSON.parse(decryptValue);
|
|
};
|
|
|
|
const stringifyStorageValue = (value: StorageValue): string => {
|
|
const stringifyValue = JSON.stringify(value);
|
|
return stringifyValue;
|
|
};
|
|
|
|
export const setLocalStorage = (key: string, value: StorageValue): void => {
|
|
try {
|
|
localStorage.setItem(key, stringifyStorageValue(value));
|
|
} catch (error) {
|
|
console.warn("[storage] localStorage set failed", { key, error });
|
|
}
|
|
};
|
|
|
|
export const getLocalStorage = (key: string): StorageValue => {
|
|
try {
|
|
const storedValue = localStorage.getItem(key);
|
|
if (storedValue === null || storedValue === "") {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
return parseStoredValue(storedValue);
|
|
} catch (decryptError) {
|
|
try {
|
|
return JSON.parse(storedValue);
|
|
} catch (fallbackError) {
|
|
console.warn("[storage] localStorage parse failed", {
|
|
key,
|
|
decryptError,
|
|
fallbackError,
|
|
});
|
|
return null;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.warn("[storage] localStorage get failed", { key, error });
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const removeLocalStorage = (key: string): void => {
|
|
localStorage.removeItem(key);
|
|
};
|
|
|
|
export const clearLocalStorage = (): void => {
|
|
localStorage.clear();
|
|
};
|
|
|
|
export const setSessionStorage = (key: string, value: StorageValue): void => {
|
|
try {
|
|
sessionStorage.setItem(key, stringifyStorageValue(value));
|
|
} catch (error) {
|
|
console.warn("[storage] sessionStorage set failed", { key, error });
|
|
}
|
|
};
|
|
|
|
export const getSessionStorage = (key: string): StorageValue => {
|
|
try {
|
|
const storedValue = sessionStorage.getItem(key);
|
|
if (storedValue === null || storedValue === "") {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
return parseStoredValue(storedValue);
|
|
} catch (decryptError) {
|
|
try {
|
|
return JSON.parse(storedValue);
|
|
} catch (fallbackError) {
|
|
console.warn("[storage] sessionStorage parse failed", {
|
|
key,
|
|
decryptError,
|
|
fallbackError,
|
|
});
|
|
return null;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.warn("[storage] sessionStorage get failed", { key, error });
|
|
return null;
|
|
}
|
|
};
|
|
|
|
export const removeSessionStorage = (key: string): void => {
|
|
sessionStorage.removeItem(key);
|
|
};
|
|
|
|
export const clearSessionStorage = (): void => {
|
|
sessionStorage.clear();
|
|
};
|