1 |
|
2 |
|
3 |
|
4 | import { catchError, EMPTY, tap } from 'rxjs';
|
5 | import { isFunction, nextTick } from '@polkadot/util';
|
6 |
|
7 |
|
8 | export function promiseTracker(resolve, reject) {
|
9 | let isCompleted = false;
|
10 | return {
|
11 | reject: error => {
|
12 | if (!isCompleted) {
|
13 | isCompleted = true;
|
14 | reject(error);
|
15 | }
|
16 | return EMPTY;
|
17 | },
|
18 | resolve: value => {
|
19 | if (!isCompleted) {
|
20 | isCompleted = true;
|
21 | resolve(value);
|
22 | }
|
23 | }
|
24 | };
|
25 | }
|
26 |
|
27 |
|
28 | function extractArgs(args, needsCallback) {
|
29 | const actualArgs = args.slice();
|
30 |
|
31 |
|
32 |
|
33 | const callback = args.length && isFunction(args[args.length - 1]) ? actualArgs.pop() : undefined;
|
34 |
|
35 |
|
36 | if (needsCallback && !isFunction(callback)) {
|
37 | throw new Error('Expected a callback to be passed with subscriptions');
|
38 | }
|
39 | return [actualArgs, callback];
|
40 | }
|
41 |
|
42 |
|
43 | function decorateCall(method, args) {
|
44 | return new Promise((resolve, reject) => {
|
45 |
|
46 | const tracker = promiseTracker(resolve, reject);
|
47 |
|
48 |
|
49 | const subscription = method(...args).pipe(catchError(error => tracker.reject(error))).subscribe(result => {
|
50 | tracker.resolve(result);
|
51 | nextTick(() => subscription.unsubscribe());
|
52 | });
|
53 | });
|
54 | }
|
55 |
|
56 |
|
57 | function decorateSubscribe(method, args, resultCb) {
|
58 | return new Promise((resolve, reject) => {
|
59 |
|
60 | const tracker = promiseTracker(resolve, reject);
|
61 |
|
62 |
|
63 | const subscription = method(...args).pipe(catchError(error => tracker.reject(error)), tap(() => tracker.resolve(() => subscription.unsubscribe()))).subscribe(result => {
|
64 |
|
65 | nextTick(() => resultCb(result));
|
66 | });
|
67 | });
|
68 | }
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | export function toPromiseMethod(method, options) {
|
74 | const needsCallback = !!(options && options.methodName && options.methodName.includes('subscribe'));
|
75 | return function (...args) {
|
76 | const [actualArgs, resultCb] = extractArgs(args, needsCallback);
|
77 | return resultCb ? decorateSubscribe(method, actualArgs, resultCb) : decorateCall((options == null ? void 0 : options.overrideNoSub) || method, actualArgs);
|
78 | };
|
79 | } |
\ | No newline at end of file |