-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathchain-and-copy-promiselike.ts
More file actions
43 lines (41 loc) · 1.06 KB
/
chain-and-copy-promiselike.ts
File metadata and controls
43 lines (41 loc) · 1.06 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
/**
* Copy the properties from a decorated promiselike object onto its chained
* actual promise.
*/
export const chainAndCopyPromiseLike = <V, T extends PromiseLike<V> & Record<string, unknown>>(
original: T,
onSuccess: (value: V) => void,
onError: (e: unknown) => void,
): T => {
return copyProps(
original,
original.then(
value => {
onSuccess(value);
return value;
},
err => {
onError(err);
throw err;
},
),
) as T;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const copyProps = <T extends Record<string, any>>(original: T, chained: T): T => {
for (const key in original) {
if (key in chained) continue;
const value = original[key];
if (typeof value === 'function') {
Object.defineProperty(chained, key, {
value: (...args: unknown[]) => value.apply(original, args),
enumerable: true,
configurable: true,
writable: true,
});
} else {
(chained as Record<string, unknown>)[key] = value;
}
}
return chained;
};