-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractor.js
More file actions
94 lines (83 loc) · 2.49 KB
/
Copy pathinteractor.js
File metadata and controls
94 lines (83 loc) · 2.49 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Creates an interactor unit
*
* @param {Function} performer
* @result {Function}
*/
module.exports = function(performer) {
// initialize hooks
var beforeHooks = [];
var afterHooks = [];
var aroundHooks = [];
/**
* Interactor Caller for context
*
* It runs the performer and hooks against a defined context
* that can be modified by the performer or any hook
*
* @param {Object} context
* @return {Object}
*/
var interactorCaller = function(context) {
// if context has failure we dont execute it
if (context.failure) {
return context;
}
// create a fail method and inject the context with it
// also delete any success variable that could have
var fail = function(options) {
Object.assign(this, options || {}, { failure: true });
};
var data = { context: Object.assign(context, { fail: fail }) };
delete data.context.success;
// create a runner function for performer and hooks
// so it actually run the performer only once regarding
// any number of around hooks applied
var run = function(hooks) {
var hook = hooks.pop();
var runner = null;
if (hooks.length == 0) {
// if there is no more around hooks we run
// any before hooks, the performer and after hooks
runner = function() {
beforeHooks.forEach(function(hook) {
hook.apply(data);
});
performer.apply(data);
afterHooks.reverse().forEach(function(hook) {
hook.apply(data);
});
};
} else {
// we run the around hook until there is non
runner = function() {
run(hooks);
};
}
// if there is no aroundHook defined we run runner directly
hook ? hook.call(data, runner) : runner();
};
// run the hooks if any and the performer
run(aroundHooks);
// if context didn't fail we set success to true
if (!data.context.failure) {
data.context.success = true;
}
// delete the extra fail method in context before returning
delete data.context.fail;
return data.context;
};
// set interactor identity (for organizer)
interactorCaller.isInteractor = true;
// set hooks methods to add hooks
interactorCaller.before = function(hook) {
beforeHooks.push(hook);
};
interactorCaller.after = function(hook) {
afterHooks.push(hook);
};
interactorCaller.around = function(hook) {
aroundHooks.push(hook);
};
return interactorCaller;
};