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