-
Notifications
You must be signed in to change notification settings - Fork 1
/
trigger-before-after.js
42 lines (34 loc) · 1.12 KB
/
trigger-before-after.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
const {
co,
isPromise,
debug
} = require('./utils')
module.exports = addTriggers
/**
* trigger will{Method} and did{Method} plugins before/after `method`
* e.g. calling strategy.send() will call plugins for willSend prior
* to running the underlying strategy.send() implementation, and didSend
* after strategy.send() is done
*/
function addTriggers (strategy, methods) {
methods.forEach(method => {
const orig = strategy[method]
strategy[method] = co(function* (...args) {
const beforeMethod = 'will' + upperFirst(method)
debug(`triggering ${beforeMethod}`)
const before = strategy._exec(beforeMethod, ...args)
if (isPromise(before)) yield before
let result = orig.call(this, ...args)
if (isPromise(result)) result = yield result
const afterArgs = args.concat(result)
const afterMethod = 'did' + upperFirst(method)
debug(`triggering ${afterMethod}`)
const after = strategy._exec(afterMethod, ...afterArgs)
if (isPromise(after)) yield after
return result
})
})
}
function upperFirst (str) {
return str[0].toUpperCase() + str.slice(1)
}