-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (60 loc) · 1.87 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
import { createAction } from 'redux-actions';
/* --------------------------example--------------------------------
export const TYPE = constants('module-name/namespace', [
'~GET_NOTE', //it will create GET_NOTE, GET_NOTE_LOADING, ...
'NORMAL_ACTION' //it will create only itself
])
------------------------------------------------------------------*/
export function constants(namespace = '', types){
const _SUFFIXES = [
'LOADING',
'PENDING',
'SUCCESS',
'ERROR',
'FAILED',
'CANCELED'
]
if(arguments.length === 1 || Array.isArray(namespace)){
types = namespace;
namespace = '';
}
if(!Array.isArray(types)){
throw 'types should be an array';
}
return types.reduce((obj,name)=>{
if(name.indexOf('~') === 0){
let type = name.slice(1);
obj[type] = (namespace ? `${namespace}/` : '') + `${type}`;
_SUFFIXES.forEach(suf=>{
obj[type + '_' + suf] = (namespace ? `${namespace}/` : '') + `${type}_${suf}`
})
}else{
obj[name] = (namespace ? `${namespace}/` : '') + `${name}`
}
return obj;
},{})
}
function camelize(str) {
return str.toLowerCase()
.split('_')
.reduce((output,word)=>{
if(!output){
output = word;
}else{
output += word.charAt(0).toUpperCase() + word.slice(1);
}
return output;
});
}
function isObject(obj) {
return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase() === 'object'
}
export function actions(TYPES){
if(!isObject(TYPES)){
throw 'TYPES should be an object'
}
return Object.keys(TYPES).reduce((actions,TYPE)=>{
actions[camelize(TYPE)] = createAction(TYPES[TYPE], null, (val,meta)=>meta);
return actions;
},{})
}