-
Notifications
You must be signed in to change notification settings - Fork 36
/
vuexSharedMutations.js
53 lines (46 loc) · 1.5 KB
/
vuexSharedMutations.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
import createDefaultStrategy from "./strategies/defaultStrategy";
export {
default as BroadcastChannelStrategy
} from "./strategies/broadcastChannel";
export { default as LocalStorageStratery } from "./strategies/localStorage";
export default ({ predicate, strategy, ...rest } = {}) => {
/* istanbul ignore next: deprecation warning */
if ("storageKey" in rest || "sharingKey" in rest) {
window.console.warn(
"Configuration directly on plugin was removed, configure specific strategies if needed"
);
}
if (!Array.isArray(predicate) && typeof predicate !== "function") {
throw new Error(
"Either array of accepted mutations or predicate function must be supplied"
);
}
const predicateFn =
typeof predicate === "function"
? predicate
: ({ type }) => predicate.indexOf(type) !== -1;
let sharingInProgress = false;
const selectedStrategy = strategy || createDefaultStrategy();
return store => {
store.subscribe((mutation, state) => {
if (sharingInProgress) {
return Promise.resolve(false);
}
return Promise.resolve(predicateFn(mutation, state)).then(shouldShare => {
if (!shouldShare) {
return;
}
selectedStrategy.share(mutation);
});
});
selectedStrategy.addEventListener(mutation => {
try {
sharingInProgress = true;
store.commit(mutation.type, mutation.payload);
} finally {
sharingInProgress = false;
}
return "done";
});
};
};