index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. function get(state, path) {
  2. return path.reduce((obj, p) => {
  3. return obj?.[p];
  4. }, state);
  5. }
  6. function set(state, path, val) {
  7. return path.slice(0, -1).reduce((obj, p) => {
  8. if (!/^(__proto__)$/.test(p)) {
  9. return obj[p] = obj[p] || {};
  10. } else
  11. return {};
  12. }, state)[path[path.length - 1]] = val, state;
  13. }
  14. function pick(baseState, paths) {
  15. return paths.reduce((substate, path) => {
  16. const pathArray = path.split(".");
  17. return set(
  18. substate,
  19. pathArray,
  20. get(baseState, pathArray)
  21. );
  22. }, {});
  23. }
  24. const isObject = (v) => typeof v === "object" && v !== null;
  25. const normalizeOptions = (options, globalOptions) => {
  26. options = isObject(options) ? options : /* @__PURE__ */ Object.create(null);
  27. return new Proxy(options, {
  28. get(t, p, r) {
  29. return Reflect.get(t, p, r) || Reflect.get(globalOptions, p, r);
  30. }
  31. });
  32. };
  33. function passage(key) {
  34. return key;
  35. }
  36. function createUnistorage(globalOptions = {}) {
  37. const { key: normalizeKey = passage } = globalOptions || {};
  38. if (globalOptions?.key) {
  39. delete globalOptions.key;
  40. }
  41. return function(ctx) {
  42. {
  43. const { store, options } = ctx;
  44. let { unistorage } = options || {};
  45. if (!unistorage)
  46. return;
  47. const {
  48. paths = null,
  49. afterRestore,
  50. beforeRestore,
  51. serializer = {
  52. serialize: JSON.stringify,
  53. deserialize: JSON.parse
  54. },
  55. key = store.$id
  56. } = normalizeOptions(unistorage, globalOptions);
  57. beforeRestore?.(ctx);
  58. const normalizedKey = normalizeKey(key);
  59. try {
  60. const fromStorage = uni.getStorageSync(normalizedKey);
  61. if (fromStorage) {
  62. store.$patch(serializer.deserialize(fromStorage));
  63. }
  64. } catch (_error) {
  65. }
  66. afterRestore?.(ctx);
  67. store.$subscribe(
  68. (_, state) => {
  69. try {
  70. const toStore = Array.isArray(paths) ? pick(state, paths) : state;
  71. uni.setStorageSync(
  72. normalizedKey,
  73. serializer.serialize(toStore)
  74. );
  75. } catch (_error) {
  76. }
  77. },
  78. { detached: true }
  79. );
  80. }
  81. };
  82. }
  83. export { createUnistorage };