· 6 years ago · Aug 29, 2019, 04:58 AM
1import _ from 'lodash';
2
3const ALLOWED_MUTATIONS = {
4 set(key) {
5 return (state, action) => ({ [key]: action[key] })
6 },
7
8 increment(key) {
9 return state => ({ [key]: state[key] + 1 });
10 },
11
12 decrement(key) {
13 return state => ({ [key]: state[key] - 1 });
14 },
15
16 updateLoading() {
17 return state => ({ loading: state.requestCount > 0 });
18 }
19};
20
21/**
22 * Experimental mutation wrapper with a chainable api
23 *
24 * e.g Usage
25 * let fn = m.set('users').andThen.increment('userCount')
26 *
27 * fn(state, action) => returns the changes to apply to the state
28 *
29 *
30 * @export
31 * @param {*} [muts=[]]
32 * @returns
33 */
34export default function Mutation(muts = []) {
35 let mutationWrapper = function (state, action) {
36 let changes = {};
37 _.chain(muts)
38 .map(fn => fn(state, action))
39 .each(change => _.extend(changes, change));
40 return changes;
41 }
42
43 _.each(ALLOWED_MUTATIONS, (mut, key) => {
44 mutationWrapper[key] = (...params) => {
45 // Build a fresh wrapper with the added mutation
46 return Mutation([ ...muts, mut(...params) ]);
47 }
48 });
49
50 mutationWrapper.andThen = mutationWrapper;
51 mutationWrapper.and = mutationWrapper;
52
53 return mutationWrapper;
54};