index.ts 903 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { STORAGE_TYPE } from '@/Frameworks/SysStorage';
  2. const useStorage = (storage: Storage) => {
  3. const setItem = <T>(key: STORAGE_TYPE, value: T) => {
  4. storage.setItem(key, value ? JSON.stringify(value) : '');
  5. };
  6. const getItem = (key: STORAGE_TYPE) => {
  7. let value: string = storage.getItem(key) || '';
  8. try {
  9. value = JSON.parse(value);
  10. return value;
  11. } catch {
  12. return value;
  13. }
  14. };
  15. const removeItem = (key: STORAGE_TYPE) => {
  16. storage.removeItem(key);
  17. };
  18. const clearAll = () => {
  19. for (const key in storage) {
  20. if (key) {
  21. storage.removeItem(key);
  22. }
  23. }
  24. };
  25. return {
  26. setItem,
  27. getItem,
  28. removeItem,
  29. clearAll,
  30. };
  31. };
  32. const SessionService = useStorage(window.sessionStorage || sessionStorage);
  33. const LocalService = useStorage(window.localStorage || sessionStorage);
  34. export { SessionService, LocalService };