/
action.js
83 lines (73 loc) · 1.84 KB
/
action.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
75
76
77
78
79
80
81
82
83
const CommonClass = require('./utils/commonClass')
const IdGenerator = require('./utils/idGenerator')
const idGenerator = IdGenerator()
class Action extends CommonClass {
/**
*/
constructor (applicaiton, id, name, method) {
super()
this.application = applicaiton
if (name !== undefined) {
this.fromJSON({
id: id || idGenerator(),
name: name || 'Unnamed',
method: method || '() => {}'
})
}
}
/**
* [toJSON description]
* @return {[type]} [description]
*/
toJSON () {
return {
id: this.id,
name: this.name,
method: this.method.toString()
}
}
/**
* [fromJSON description]
* @param {[type]} json [description]
* @return {[type]} [description]
*/
fromJSON (json) {
let result
if (typeof json === 'string') {
result = this.loadFlattened(json)
} else if (json instanceof Object && !(json instanceof Array)) {
result = json
} else {
throw new Error(`Expected Action JSON to be a string or an object, but got a ${typeof json} instead`)
}
this.id = result.id
this.name = result.name
if (typeof result.method === 'string') {
this.method = new Function(`return ${result.method}`)()
} else {
this.method = result.method
}
return this
}
/**
* [execute description]
* @param {[type]} actionContext [description]
* @return {[type]} [description]
*/
async execute (actionContext) {
return this.method.call(actionContext)
}
}
/**
* [load description]
* @param {[type]} actions [description]
* @return {[type]} [description]
*/
Action.load = function load (actions) {
const results = []
for (const name in actions) {
results.push(new Action(undefined, undefined, name, actions[name]))
}
return results
}
module.exports = Action