-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcreate.js
61 lines (56 loc) · 1.4 KB
/
create.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
const debug = require("debug")("JustAList:CreateAction")
/**
* Call list.create method to add result to slice.items
*
* @param {string} listName Slice name - for error messages
* @param {Function} dispatch Redux dispatch
* @param {Function} api API method
* @param {Function} onChange Appy on items array before changing state
*
* @param {object} data Model data
* @param {Array} rest Other paramaters passed when calling list.create
*
* @returns {Promise<object<error, result>>}
*/
export const createAction = ({
listName,
dispatch,
api,
hasDispatchStart,
hasDispatchEnd,
onChange,
}) => (data, ...rest) => {
if (hasDispatchStart) {
dispatch({
type: `${listName}_CREATE_START`,
payload: {
listName,
items: Array.isArray(data) ? data : [data],
},
})
}
return Promise.resolve()
.then(() => api(data, ...rest))
.then(result => {
if (hasDispatchEnd) {
dispatch({
type: `${listName}_CREATE_END`,
payload: {
listName,
items: Array.isArray(result) ? result : [result],
onChange,
},
})
}
return { result }
})
.catch(error => {
// reducer and promise resolve the same data
error.date = new Date()
dispatch({
type: `${listName}_CREATE_ERROR`,
payload: error,
})
return { error }
})
}