UNPKG

3.21 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.toPromiseMethod = exports.promiseTracker = void 0;
4const rxjs_1 = require("rxjs");
5const util_1 = require("@polkadot/util");
6function 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}
24exports.promiseTracker = promiseTracker;
25function extractArgs(args, needsCallback) {
26 const actualArgs = args.slice();
27 // If the last arg is a function, we pop it, put it into callback.
28 // actualArgs will then hold the actual arguments to be passed to `method`
29 const callback = (args.length && (0, util_1.isFunction)(args[args.length - 1]))
30 ? actualArgs.pop()
31 : undefined;
32 // When we need a subscription, ensure that a valid callback is actually passed
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}
38function decorateCall(method, args) {
39 return new Promise((resolve, reject) => {
40 // single result tracker - either reject with Error or resolve with Codec result
41 const tracker = promiseTracker(resolve, reject);
42 // encoding errors reject immediately, any result unsubscribes and resolves
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}
51function decorateSubscribe(method, args, resultCb) {
52 return new Promise((resolve, reject) => {
53 // either reject with error or resolve with unsubscribe callback
54 const tracker = promiseTracker(resolve, reject);
55 // errors reject immediately, the first result resolves with an unsubscribe promise, all results via callback
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 // queue result (back of queue to clear current)
60 (0, util_1.nextTick)(() => resultCb(result));
61 });
62 });
63}
64/**
65 * @description Decorate method for ApiPromise, where the results are converted to the Promise equivalent
66 */
67function 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}
76exports.toPromiseMethod = toPromiseMethod;