UNPKG

2.48 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _lodash = require("lodash");
9
10var _constants = require("./constants");
11
12var _helpers = require("../helpers");
13
14var _default = (state = {}, {
15 type,
16 data,
17 err,
18 key,
19 pluralized
20}) => {
21 if (!key) {
22 throw new Error('Key required for managing state');
23 }
24
25 const resource = key;
26 const resources = pluralized;
27 const handlers = {
28 [_constants.FETCHING]() {
29 return {
30 fetching: true
31 };
32 },
33
34 [_constants.FETCHED]: () => ({ ...state,
35 ...data,
36 fetchingError: !(0, _helpers.isEmpty)(err),
37 fetching: false,
38 err
39 }),
40
41 [_constants.UPDATED]() {
42 const next = (0, _lodash.get)(data, resource, {});
43 const prev = { ...state
44 };
45
46 if (resource in prev) {
47 prev[resource] = next;
48 } else if (resources in prev) {
49 prev[resources] = (0, _lodash.get)(prev, resources, []).map(item => next.id === item.id ? next : item);
50 }
51
52 return (0, _lodash.merge)({}, prev, data);
53 },
54
55 [_constants.CREATED]() {
56 if ((0, _helpers.isEmpty)(data)) return state;
57 const next = (0, _lodash.get)(data, resource, {});
58 const prev = { ...state
59 };
60
61 if (resource in prev) {
62 prev[resource] = next;
63 } else {
64 prev[resources] = Array.isArray(state[resources]) ? [next, ...state[resources]] : [next];
65 }
66
67 return prev;
68 },
69
70 /**
71 * @TODO:
72 * Find better solution.
73 */
74 [_constants.DELETED]() {
75 return (0, _helpers.isEmpty)(data) ? state : { ...state,
76 [resource]: Array.isArray(state[resource]) ? state[resource].filter(({
77 id
78 }) => id !== data.id) : state[resource],
79 [resources]: Array.isArray(state[resources]) ? state[resources].filter(({
80 id
81 }) => id !== data.id) : state[resources]
82 };
83 },
84
85 /**
86 * @TODO:
87 * Find better solution.
88 */
89 [_constants.DELETED_MANY]() {
90 return (0, _helpers.isEmpty)(data) ? state : { ...state,
91 [resource]: Array.isArray(state[resource]) ? state[resource].filter(({
92 id
93 }) => !data.ids.includes(id)) : null,
94 [resources]: Array.isArray(state[resources]) ? state[resources].filter(({
95 id
96 }) => !data.ids.includes(id)) : null
97 };
98 }
99
100 };
101 return (0, _helpers.getFn)(handlers, type);
102};
103
104exports.default = _default;
\No newline at end of file