pinia-persist-uni.es.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const isH5 = typeof alert === "function";
  2. const updateStorage = (strategy, store, options) => {
  3. const storage = strategy.storage;
  4. const storeKey = strategy.key || store.$id;
  5. const isCustomStorage = isH5 || (options == null ? void 0 : options.enforceCustomStorage);
  6. if (strategy.paths) {
  7. const partialState = strategy.paths.reduce((finalObj, key) => {
  8. finalObj[key] = store.$state[key];
  9. return finalObj;
  10. }, {});
  11. if (isCustomStorage && storage) {
  12. storage.setItem(storeKey, JSON.stringify(partialState));
  13. } else {
  14. uni.setStorage({ key: storeKey, data: JSON.stringify(partialState) });
  15. }
  16. } else if (isCustomStorage && storage) {
  17. storage.setItem(storeKey, JSON.stringify(store.$state));
  18. } else {
  19. uni.setStorage({ key: storeKey, data: JSON.stringify(store.$state) });
  20. }
  21. };
  22. var index = ({ options, store }) => {
  23. var _a, _b, _c, _d, _e, _f;
  24. if ((_a = options.persist) == null ? void 0 : _a.enabled) {
  25. const defaultStrat = [
  26. {
  27. key: store.$id,
  28. storage: ((_b = options.persist) == null ? void 0 : _b.H5Storage) || (window == null ? void 0 : window.sessionStorage)
  29. }
  30. ];
  31. const strategies = ((_d = (_c = options.persist) == null ? void 0 : _c.strategies) == null ? void 0 : _d.length) ? (_e = options.persist) == null ? void 0 : _e.strategies : defaultStrat;
  32. strategies.forEach((strategy) => {
  33. var _a2, _b2;
  34. const storage = strategy.storage || ((_a2 = options.persist) == null ? void 0 : _a2.H5Storage) || (window == null ? void 0 : window.sessionStorage);
  35. const storeKey = strategy.key || store.$id;
  36. let storageResult;
  37. if (isH5 || ((_b2 = options.persist) == null ? void 0 : _b2.enforceCustomStorage)) {
  38. storageResult = storage.getItem(storeKey);
  39. } else {
  40. storageResult = uni.getStorageSync(storeKey);
  41. }
  42. if (storageResult) {
  43. store.$patch(JSON.parse(storageResult));
  44. updateStorage(strategy, store, options.persist);
  45. }
  46. });
  47. store.$subscribe(() => {
  48. strategies.forEach((strategy) => {
  49. updateStorage(strategy, store, options.persist);
  50. });
  51. }, { detached: ((_f = options.persist) == null ? void 0 : _f.detached) ? true : false });
  52. }
  53. };
  54. export { index as default };