forked from robinvdvleuten/vuex-persistedstate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (62 loc) · 1.82 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import merge from 'deepmerge';
import * as shvl from 'shvl';
export default function(options, storage, key) {
options = options || {};
storage = options.storage || (window && window.localStorage);
key = options.key || 'vuex';
function canWriteStorage(storage) {
try {
storage.setItem('@@', 1);
storage.removeItem('@@');
return true;
} catch (e) {}
return false;
}
function getState(key, storage, value) {
try {
return (value = storage.getItem(key)) && typeof value !== 'undefined'
? JSON.parse(value)
: undefined;
} catch (err) {}
return undefined;
}
function filter() {
return true;
}
function setState(key, state, storage) {
return storage.setItem(key, JSON.stringify(state));
}
function reducer(state, paths) {
return paths.length === 0
? state
: paths.reduce(function(substate, path) {
return shvl.set(substate, path, shvl.get(state, path));
}, {});
}
function subscriber(store) {
return function(handler) {
return store.subscribe(handler);
};
}
if (!canWriteStorage(storage)) {
throw new Error('Invalid storage instance given');
}
return function(store) {
const savedState = shvl.get(options, 'getState', getState)(key, storage);
if (typeof savedState === 'object' && savedState !== null) {
store.replaceState(merge(store.state, savedState, {
arrayMerge: options.arrayMerger || function (store, saved) { return saved },
clone: false,
}));
}
(options.subscriber || subscriber)(store)(function(mutation, state) {
if ((options.filter || filter)(mutation)) {
(options.setState || setState)(
key,
(options.reducer || reducer)(state, options.paths || []),
storage
);
}
});
};
};