pinia-persist-uni.es.js 2.4 KB

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