Move Rx API wrapper into api (#87)

* Move Rx API wrapper into api

* Bump
This commit is contained in:
Jaco Greeff
2018-05-07 12:01:09 +02:00
committed by GitHub
parent 2c6a853f73
commit 92c7c2cc1f
25 changed files with 545 additions and 12 deletions
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { ProviderInterface } from '@polkadot/api-provider/types';
const { BehaviorSubject } = require('rxjs/BehaviorSubject');
module.exports = function connected (provider: ProviderInterface): rxjs$BehaviorSubject<boolean> {
const subject = new BehaviorSubject(provider.isConnected());
provider.on('connected', () => subject.next(true));
provider.on('disconnected', () => subject.next(false));
return subject;
};
+18
View File
@@ -0,0 +1,18 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { ProviderInterface } from '@polkadot/api-provider/types';
import type { RxApiInterface } from '../types';
const createConnected = require('./connected');
module.exports = function exposed (provider: ProviderInterface): RxApiInterface {
const connected = createConnected(provider);
return {
isConnected: (): rxjs$BehaviorSubject<boolean> =>
connected
};
};
+10
View File
@@ -0,0 +1,10 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
const WS_URL = 'ws://127.0.0.1:9944';
module.exports = {
WS_URL
};
+29
View File
@@ -0,0 +1,29 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { ProviderInterface } from '@polkadot/api-provider/types';
import type { InterfaceTypes } from '@polkadot/api-jsonrpc/types';
import type { RxApiInterface } from './types';
const createApi = require('@polkadot/api');
const interfaces = require('@polkadot/api-jsonrpc');
const createWs = require('@polkadot/api-provider/ws');
const createExposed = require('./api');
const defaults = require('./defaults');
const createInterface = require('./interface');
module.exports = function rxApi (provider?: ProviderInterface = createWs(defaults.WS_URL)): RxApiInterface {
const api = createApi(provider);
const exposed = createExposed(provider);
return Object
.keys(interfaces)
.reduce((result, type: InterfaceTypes) => {
result[type] = createInterface(api, type);
return result;
}, exposed);
};
+22
View File
@@ -0,0 +1,22 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
jest.mock('@polkadot/api-provider/ws', () => () => ({
isConnected: () => true,
on: () => true,
send: () => true
}));
jest.mock('./interface', () => (api, sectionName) => sectionName);
const createApi = require('./index');
describe('createApi', () => {
it('creates an instance with all sections', () => {
expect(
Object.keys(createApi())
).toEqual([
'isConnected', 'author', 'chain', 'state'
]);
});
});
+23
View File
@@ -0,0 +1,23 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { ApiInterface, ApiInterface$Section } from '@polkadot/api/types';
import type { InterfaceTypes } from '@polkadot/api-jsonrpc/types';
import type { RxApiInterface$Section } from './types';
const observable = require('./observable');
module.exports = function createInterface (api: ApiInterface, sectionName: InterfaceTypes): RxApiInterface$Section {
const section: ApiInterface$Section = api[sectionName];
return Object
.keys(section)
.filter((name) => !['subscribe', 'unsubscribe'].includes(name))
.reduce((observables, name) => {
observables[name] = observable(`${sectionName}_${name}`, name, section);
return observables;
}, ({}: $Shape<RxApiInterface$Section>));
};
+37
View File
@@ -0,0 +1,37 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
jest.mock('./observable', () => (subName, name, section) => `${subName}_${name}_${Object.keys(section).join(':')}`);
const createInterface = require('./interface');
describe('createInterface', () => {
let api;
let int;
beforeEach(() => {
api = {
chain: {
foo: 'test',
bar: 'test',
subscribe: 'noInclude',
unsubscribe: 'noInclude'
},
state: {
baz: 'test'
}
};
int = createInterface(api, 'chain');
});
it('creates observables for all relevant methods', () => {
expect(
int
).toEqual({
foo: 'chain_foo_foo_foo:bar:subscribe:unsubscribe',
bar: 'chain_bar_bar_foo:bar:subscribe:unsubscribe'
});
});
});
+35
View File
@@ -0,0 +1,35 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { ApiInterface$Section } from '@polkadot/api/types';
type Cached$Name = string;
type Cached$ParamJson = string;
type CachedMap = {
[Cached$Name]: {
[Cached$ParamJson]: rxjs$BehaviorSubject<*>
}
};
const subject = require('./subject');
const cacheMap: CachedMap = {};
module.exports = function cached (subName: string, name: string, section: ApiInterface$Section): (...params: Array<mixed>) => rxjs$BehaviorSubject<*> {
if (!cacheMap[subName]) {
cacheMap[subName] = {};
}
return (...params: Array<mixed>): rxjs$BehaviorSubject<*> => {
const paramStr = JSON.stringify(params);
if (!cacheMap[subName][paramStr]) {
cacheMap[subName][paramStr] = subject(name, params, section);
}
return cacheMap[subName][paramStr];
};
};
@@ -0,0 +1,80 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
const cachedSubscription = require('./cached');
describe('cached', () => {
let creator;
let section;
beforeEach(() => {
const subMethod = jest.fn((name, ...params) => {
return Promise.resolve(12345);
});
subMethod.unsubscribe = jest.fn(() => {
return Promise.resolve(true);
});
const resMethod = jest.fn((name, ...params) => {
return Promise.resolve(12345);
});
section = {
resMethod,
subMethod
};
creator = cachedSubscription('test', 'subMethod', section);
});
it('creates a single observable', () => {
creator(123).subscribe((value) => {});
expect(
section.subMethod
).toHaveBeenCalledWith(123, expect.anything());
});
it('creates a single observable (multiple calls)', () => {
const observable1 = creator(123);
observable1.subscribe((value) => {});
const observable2 = creator(123);
observable2.subscribe((value) => {});
expect(
observable2
).toEqual(observable1);
});
it('creates multiple observers for different values', () => {
const observable1 = creator(123);
observable1.subscribe((value) => {});
const observable2 = creator(456);
observable2.subscribe((value) => {});
expect(
observable2
).not.toEqual(observable1);
});
it('functions as an subject', (done) => {
const subject = creator(123);
subject.subscribe((value) => {
if (value) {
expect(value).toEqual('test');
done();
}
});
subject.next('test');
});
});
+22
View File
@@ -0,0 +1,22 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { ApiInterface$Section } from '@polkadot/api/types';
const { fromPromise } = require('rxjs/observable/fromPromise');
const isFunction = require('@polkadot/util/is/function');
const cached = require('./cached');
module.exports = function observable (subName: string, name: string, section: ApiInterface$Section): (...params: Array<mixed>) => rxjs$Observable<*> | rxjs$BehaviorSubject<*> {
if (isFunction(section[name].unsubscribe)) {
return cached(subName, name, section);
}
return (...params: Array<mixed>): rxjs$Observable<*> =>
fromPromise(
section[name].apply(null, params)
);
};
@@ -0,0 +1,38 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
const createObservable = require('./index');
describe('observable', () => {
let section;
beforeEach(() => {
const withSub = () => {};
withSub.unsubscribe = jest.fn();
section = {
'test_noSub': jest.fn(() => Promise.resolve(true)),
'test_withSub': withSub,
subscribe: jest.fn((name, params, _callback) => {
return Promise.resolve(12345);
}),
unsubscribe: jest.fn(() => {
return Promise.resolve(true);
})
};
});
it('creates a single-shot observable', () => {
expect(
createObservable('test_noSub', 'test_noSub', section)()
).toBeDefined();
});
it('creates a subscription observable', () => {
expect(
createObservable('test_withSub', 'test_withSub', section)()
).toBeDefined();
});
});
+44
View File
@@ -0,0 +1,44 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { ApiInterface$Section } from '@polkadot/api/types';
const { BehaviorSubject } = require('rxjs/BehaviorSubject');
const { Observable } = require('rxjs/Observable');
// flowlint-next-line unclear-type:off
module.exports = function subscription (name: string, params: Array<mixed>, section: ApiInterface$Section, unsubCallback?: () => void): rxjs$BehaviorSubject<any> {
const subject = new BehaviorSubject();
Observable
// flowlint-next-line unclear-type:off
.create((observer: rxjs$IObserver<any>): Function => {
const callback = (error, result) => {
if (error) {
return;
}
observer.next(result);
};
const fn = section[name];
const subParams: Array<mixed> = [].concat(params, [callback]);
const subscribe = fn.apply(null, subParams);
return (): void => {
subscribe
// flowlint-next-line unclear-type:off
.then((subscriptionId) => fn.unsubscribe(((subscriptionId: any): number)))
.then(() => {
if (unsubCallback) {
unsubCallback();
}
});
};
})
.subscribe(subject);
return subject;
};
@@ -0,0 +1,73 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
const createObservable = require('./subject');
describe('subject', () => {
const params = [123, false];
let callback;
let section;
let subscription;
let observable;
beforeEach(() => {
const subMethod = jest.fn((name, ...params) => {
callback = params.pop();
return Promise.resolve(12345);
});
subMethod.unsubscribe = jest.fn(() => {
return Promise.resolve(true);
});
section = {
subMethod
};
observable = createObservable('subMethod', params, section);
});
afterEach(() => {
if (subscription) {
subscription.unsubscribe();
}
});
it('subscribes via the api section', (done) => {
observable.subscribe((value) => {
if (value) {
expect(
section.subMethod
).toHaveBeenCalledWith(123, false, expect.anything());
done();
}
});
callback(null, 'test');
});
it('returns the observable value', (done) => {
subscription = observable.subscribe((value) => {
if (value) {
expect(value).toEqual('test');
done();
}
});
callback(null, 'test');
});
it('ignores errors, returns the observable value', (done) => {
subscription = observable.subscribe((value) => {
if (value) {
expect(value).toEqual('test');
done();
}
});
callback(new Error('error'));
callback(null, 'test');
});
});
+17
View File
@@ -0,0 +1,17 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
import type { InterfaceTypes } from '@polkadot/api-jsonrpc/types';
export type RxApiInterface$Method = (...params: Array<mixed>) => rxjs$Observable<*> | rxjs$BehaviorSubject<*>;
export type RxApiInterface$Section = {
[string]: RxApiInterface$Method
};
export type RxApiInterface = {
isConnected: () => rxjs$BehaviorSubject<boolean>;
[InterfaceTypes]: RxApiInterface$Section;
};