/
index.js
54 lines (45 loc) · 1.31 KB
/
index.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
function createInjectPoint(obj, method) {
let target = obj
if (!(method in target)) {
target = target.prototype
}
if (!target) {
throw `${method} not in obj`
}
const origin = target[method]
const wayBack = '__cam_'+method
if (!target[wayBack]) {
target[wayBack] = origin
}
return {target, origin}
}
module.exports = {
before(obj, method, inject) {
const {target, origin} = createInjectPoint(obj, method)
target[method] = function () {
inject(this, ...arguments)
return origin.call(this, ...arguments)
}
},
after(obj, method, inject) {
const {target, origin} = createInjectPoint(obj, method)
target[method] = function () {
const result = origin.call(this, ...arguments)
returninject(this, result)
return result
}
},
replace(obj, method, inject) {
const {target, origin} = createInjectPoint(obj, method)
target[method] = function() {
return inject(this, origin, ...arguments)
}
},
leave(obj, method) {
const {target} = createInjectPoint(obj, method)
const wayBack = '__cam_'+method
if (target[wayBack]) {
target[method] = target[wayBack]
}
}
}