pinia-persist.es.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. const updateStorage = (strategy, store) => {
  2. const storage = strategy.storage || sessionStorage;
  3. const storeKey = strategy.key || store.$id;
  4. if (strategy.paths) {
  5. const partialState = strategy.paths.reduce((finalObj, key) => {
  6. finalObj[key] = store.$state[key];
  7. return finalObj;
  8. }, {});
  9. storage.setItem(storeKey, JSON.stringify(partialState));
  10. } else {
  11. storage.setItem(storeKey, JSON.stringify(store.$state));
  12. }
  13. };
  14. var index = ({ options, store }) => {
  15. var _a, _b, _c, _d;
  16. if ((_a = options.persist) == null ? void 0 : _a.enabled) {
  17. const defaultStrat = [{
  18. key: store.$id,
  19. storage: sessionStorage
  20. }];
  21. const strategies = ((_c = (_b = options.persist) == null ? void 0 : _b.strategies) == null ? void 0 : _c.length) ? (_d = options.persist) == null ? void 0 : _d.strategies : defaultStrat;
  22. strategies.forEach((strategy) => {
  23. const storage = strategy.storage || sessionStorage;
  24. const storeKey = strategy.key || store.$id;
  25. const storageResult = storage.getItem(storeKey);
  26. if (storageResult) {
  27. store.$patch(JSON.parse(storageResult));
  28. updateStorage(strategy, store);
  29. }
  30. });
  31. store.$subscribe(() => {
  32. strategies.forEach((strategy) => {
  33. updateStorage(strategy, store);
  34. });
  35. });
  36. }
  37. };
  38. export { index as default, updateStorage };