-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallbacks.js
77 lines (69 loc) · 1.54 KB
/
callbacks.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
/**
* @example
* @before("valid");
* generateSlug() {
* this.slug = paramCase(this.name);
* }
* @param method
*/
export function before(...methods) {
return (target, key, descriptor) => {
methods.forEach((method) => {
const original = target[method];
const callback = descriptor.value;
const value = () => {
callback();
return original();
};
target.defineProperty(method, { value });
});
};
}
/**
* @example
* @after("save");
* deliverConfirmationEmail() {
* UserMailer.deliver("confirmation", { user: this })
* }
* @param method
*/
export function after(...methods) {
return (target, key, descriptor) => {
methods.forEach((method) => {
const original = target[method];
const callback = descriptor.value;
const value = () => {
const rv = original();
callback(rv);
return rv;
};
target.defineProperty(method, { value });
});
};
}
/**
* @example
* @around("update");
* lock(update) {
* this.locked = true;
* const rv = update();
* this.locked = false;
*
* return rv;
* }
* @param method
*/
export function around(...methods) {
return (target, key, descriptor) => {
methods.forEach((method) => {
const original = target[method];
const callback = descriptor.value;
const value = () => callback(original);
target.defineProperty(method, { value });
});
};
}
/**
* Callbacks can be used on any object
*/
export default { before, after, around };