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