-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxymise.ts
59 lines (55 loc) · 1.7 KB
/
proxymise.ts
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
/**
* @file proxymise.ts
* @author Brandon Kalinowski
* @copyright 2020 Brandon Kalinowski (brandonkal)
* @copyright 2018 Ilya Kozhevnikov <[email protected]>
* @description Chainable Promise Proxy utility.
* Proxymise allows for method and property chaining without need for intermediate
* then() or await for cleaner and simpler code.
* @see https://github.com/kozhevnikov/proxymise
* @license MIT
*/
export function proxymise(target: any) {
if (typeof target === "object") {
const proxy = () => target;
//@ts-ignore: extending proto for library
proxy.__proxy__ = true;
return new Proxy(proxy, handler);
}
return typeof target === "function" ? new Proxy(target, handler) : target;
}
const handler = {
get(target: any, property: any, receiver: any): any {
if (target.__proxy__) target = target();
if (
property !== "then" &&
property !== "catch" &&
typeof target.then === "function"
) {
return proxymise(
target.then((value: any) => get(value, property, receiver)),
);
}
return proxymise(get(target, property, receiver));
},
apply(target: any, thisArg: any, argumentsList: any): any {
if (target.__proxy__) target = target();
if (typeof target.then === "function") {
return proxymise(
target.then((value: any) =>
Reflect.apply(value, thisArg, argumentsList)
),
);
}
return proxymise(Reflect.apply(target, thisArg, argumentsList));
},
};
const get = (target: any, property: any, receiver: any) => {
const value = typeof target === "object"
? Reflect.get(target, property, receiver)
: target[property];
if (typeof value === "function" && typeof value.bind === "function") {
return Object.assign(value.bind(target), value);
}
return value;
};