diff --git a/packages/api/src/Base.ts b/packages/api/src/Base.ts index 6807a60f3f..1cf2bababa 100644 --- a/packages/api/src/Base.ts +++ b/packages/api/src/Base.ts @@ -46,12 +46,12 @@ export default abstract class ApiBase implements ApiBaseInterface * * ```javascript - * import Api from '@polkadot/api/rx'; + * import Api from '@polkadot/api/promise'; * - * new Api().isReady.subscribe((api) => { - * api.rpc.subscribeNewHead().subscribe((header) => { - * console.log(`new block #${header.blockNumber.toNumber()}`); - * }); + * const api = new Api().isReady(); + * + * api.rpc.subscribeNewHead((header) => { + * console.log(`new block #${header.blockNumber.toNumber()}`); * }); * ``` */ @@ -99,11 +99,9 @@ export default abstract class ApiBase implements ApiBaseInterface * * ```javascript - * api.query.balances - * .freeBalance() - * .subscribe((balance) => { - * console.log('new balance', balance); - * }); + * api.query.balances.freeBalance(, (balance) => { + * console.log('new balance', balance); + * }); * ``` */ get query (): S { @@ -121,11 +119,9 @@ export default abstract class ApiBase implements ApiBaseInterface * * ```javascript - * api.rpc.chain - * .subscribeNewHead() - * .subscribe((header) => { - * console.log('new header', header); - * }); + * api.rpc.chain.subscribeNewHead((header) => { + * console.log('new header', header); + * }); * ``` */ get rpc (): R { @@ -142,8 +138,7 @@ export default abstract class ApiBase implements ApiBaseInterface, ) * .sign(, , ) - * .send() - * .subscribe((status) => { + * .send((status) => { * console.log('tx status', status); * }); * ``` @@ -164,7 +159,7 @@ export default abstract class ApiBase implements ApiBaseInterface * * ```javascript - * * api.on('disconnected', () => { + * api.on('disconnected', () => { * console.log('API has been connected to the endpoint'); * }); * diff --git a/packages/api/src/promise/Combinator.ts b/packages/api/src/promise/Combinator.ts new file mode 100644 index 0000000000..cd1310b468 --- /dev/null +++ b/packages/api/src/promise/Combinator.ts @@ -0,0 +1,54 @@ +// Copyright 2017-2018 @polkadot/api authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import { isFunction } from '@polkadot/util'; + +export type CombinatorCallback = (value: Array) => any; +export type CombinatorFunction = (cb: (value: any) => void) => any; + +export default class Combinator { + protected _allHasFired: boolean = false; + protected _callback: CombinatorCallback; + protected _fired: Array = []; + protected _results: Array = []; + + constructor (fns: Array, callback: CombinatorCallback) { + this._callback = callback; + + fns.forEach((fn, index) => { + this._fired.push(false); + + fn(this.createCallback(index)); + }); + } + + protected allHasFired (): boolean { + if (!this._allHasFired) { + this._allHasFired = this._fired.filter((hasFired) => !hasFired).length === 0; + } + + return this._allHasFired; + } + + protected createCallback (index: number) { + return (value: any): void => { + this._fired[index] = true; + this._results[index] = value; + + this.triggerUpdate(); + }; + } + + protected triggerUpdate (): void { + if (!isFunction(this._callback) || !this.allHasFired()) { + return; + } + + try { + this._callback(this._results); + } catch (error) { + // swallow, we don't want the handler to trip us up + } + } +} diff --git a/packages/api/src/promise/Combinators.spec.ts b/packages/api/src/promise/Combinators.spec.ts new file mode 100644 index 0000000000..3864a90985 --- /dev/null +++ b/packages/api/src/promise/Combinators.spec.ts @@ -0,0 +1,81 @@ +// Copyright 2017-2018 @polkadot/api authors & contributors +// This software may be modified and distributed under the terms +// of the ISC license. See the LICENSE file for details. + +import Combinator from './Combinator'; + +describe('Combinator', () => { + it('it triggers on all values', (done) => { + let count = 0; + const fns: Array<(value: any) => void> = []; + const combinator = new Combinator( + [ + (cb) => fns.push(cb) + ], + (value: Array) => { + expect(value[0]).toEqual(`test${count}`); + + count++; + + if (count === 3) { + done(); + } + } + ); + + fns[0]('test0'); + fns[0]('test1'); + fns[0]('test2'); + + expect(combinator).toBeDefined(); + }); + + it('combines values from 2 sources, firing when it has all results', (done) => { + const fns: Array<(value: any) => void> = []; + const combinator = new Combinator( + [ + (cb) => fns.push(cb), + (cb) => fns.push(cb) + ], + (value: Array) => { + expect(value).toEqual(['test0', 'test1']); + + done(); + } + ); + + fns[0]('test0'); + fns[1]('test1'); + + expect(combinator).toBeDefined(); + }); + + it('combines values from 2 sources, allowing multiple updates', (done) => { + let count = 0; + const fns: Array<(value: any) => void> = []; + const combinator = new Combinator( + [ + (cb) => fns.push(cb), + (cb) => fns.push(cb) + ], + (value: Array) => { + expect(value).toEqual( + count === 0 + ? ['test0', 'test1'] + : ['test2', 'test1']); + + count++; + + if (count === 2) { + done(); + } + } + ); + + fns[0]('test0'); + fns[1]('test1'); + fns[0]('test2'); + + expect(combinator).toBeDefined(); + }); +}); diff --git a/packages/api/src/promise/SubmittableExtrinsic.spec.js b/packages/api/src/promise/SubmittableExtrinsic.spec.ts similarity index 95% rename from packages/api/src/promise/SubmittableExtrinsic.spec.js rename to packages/api/src/promise/SubmittableExtrinsic.spec.ts index b1281171f7..4dc66e0b93 100644 --- a/packages/api/src/promise/SubmittableExtrinsic.spec.js +++ b/packages/api/src/promise/SubmittableExtrinsic.spec.ts @@ -9,7 +9,7 @@ import Method from '@polkadot/types/Method'; import SubmittableExtrinsic from './SubmittableExtrinsic'; describe('SubmittableExtrinsic', () => { - let api; + let api: any; beforeEach(() => { Method.injectExtrinsics(extrinsics); @@ -28,7 +28,9 @@ describe('SubmittableExtrinsic', () => { const result = await new SubmittableExtrinsic( api, new Extrinsic('0x010200ea51b75b00000000') - ).send(() => { }); + ).send(() => { + // ignore + }); expect(result).toEqual('submitAndWatchExtrinsic'); }); diff --git a/packages/api/src/promise/index.ts b/packages/api/src/promise/index.ts index 42c486f4b0..8cf7c6a1b7 100644 --- a/packages/api/src/promise/index.ts +++ b/packages/api/src/promise/index.ts @@ -13,6 +13,7 @@ import { StorageFunction } from '@polkadot/types/StorageKey'; import { isFunction } from '@polkadot/util'; import ApiBase from '../Base'; +import Combinator, { CombinatorCallback, CombinatorFunction } from './Combinator'; import SubmittableExtrinsic from './SubmittableExtrinsic'; /** @@ -165,6 +166,30 @@ export default class ApiPromise extends ApiBase void` + * @param callback A callback that will return an Array of all the values this combinator has been applied to + * @example + *
+ * + * ```javascript + * const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7'; + * + * // combines values from balance & nonce as it updates + * api.combineLatest([ + * (cb) => api.rpc.chain.subscribeNewHead(cb), + * (cb) => api.query.balances.freeBalance(address, cb), + * (cb) => api.query.system.accountNonce(address, cb) + * ], ([head, balance, nonce]) => { + * console.log(`#${head.number}: You have ${balance} units, with ${nonce} transactions sent`); + * }); + * ``` + */ + combineLatest (fns: Array, callback: CombinatorCallback): Combinator { + return new Combinator(fns, callback); + } + protected decorateExtrinsics (extrinsics: Extrinsics): SubmittableExtrinsics { return Object.keys(extrinsics).reduce((result, sectionName) => { const section = extrinsics[sectionName];