-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprepAction.js
More file actions
executable file
·69 lines (58 loc) · 1.55 KB
/
prepAction.js
File metadata and controls
executable file
·69 lines (58 loc) · 1.55 KB
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
// prepAction(action, state, glossary, now) => action
function prepAction (action, state, glossary, now) {
let entry, msg
let {type} = action
entry = glossary[type]
// entry exists?
if (!entry) {
msg = "Action type '" + type + "' is missing entry"
return handleErr(action, "unknownActionType", msg)
}
let {spec, init, check, turn} = entry
// Action formatted?
if (spec) {
if (typeof(spec) === "function") {
try {
spec(action)
} catch (e) {
return handleErr(action, "wrongFormat", e.message)
}
} else {
let key
for (key in spec) {
if (typeof(action[key]) !== spec[key]) {
msg = key + " should be of type " + spec[key]
return handleErr(action, "wrongFormat", msg)
}
}
}
}
if (init) {
action = init(state, action)
if (!action) {
throw new Error("Init for action type " +type+ " has no return.")
}
}
// Action valid against state?
if (check) {
msg = check(state, action)
if (msg) {
return handleErr(action, "invalid", msg)
}
}
// Extend action with relevant data
let actionExtend = {
id: String(Math.random()).substr(2)
}
if (turn) {
actionExtend.turn = state.times.turn + turn
} else {
actionExtend.time = now + (entry.time || 0)
}
return Object.assign({}, action, actionExtend)
}
function handleErr(obj, type, msg) {
let err = {type, msg}
return Object.assign({}, obj, {err})
}
module.exports = prepAction