-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.js
56 lines (48 loc) · 1.08 KB
/
command.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
'use strict'
/**
* Command
* - Encapsulates calling of a method as an object
* - Decouples the execution from the implementation
* - Less fragile implementation
* - UNDO operations, saving state
*
* Have used in DATABASES to rollback transitions if
* anything get wrong
*/
let repo = {
tasks: {},
commands: [],
get: function (id) {
return {name: 'Task #1'}
},
save: function (task) {
repo.tasks[task.id] = task
return {name: task.name, status: 'OK'}
},
// ROLLBACK!
replay: function () {
for (let i = 0; i < repo.commands.length; i++) {
let command = repo.commands[i]
repo.executeNonLog(command.name, command.obj)
}
}
}
repo.executeNonLog = function (name) {
let args = Array.prototype.slice.call(arguments, 1)
if (repo[name]) {
return repo[name].apply(repo, args)
}
return false
}
repo.execute = function (name) {
let args = Array.prototype.slice.call(arguments, 1)
repo.commands.push({
name: name,
obj: args[0]
})
if (repo[name]) {
return repo[name].apply(repo, args)
}
return false
}
module.exports = repo