TypeScript conversion (#101)
* Auto-conversion * ES6 import/export * WIP... * WIP... * And... we are TS typed, some good, some bad, some better, some worse * Tests passing
This commit is contained in:
@@ -0,0 +1 @@
|
||||
module.exports = require('./babel.config.js');
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
[ignore]
|
||||
<PROJECT_ROOT>/build
|
||||
<PROJECT_ROOT>/packages/.*/build
|
||||
|
||||
[include]
|
||||
|
||||
[libs]
|
||||
node_modules/@polkadot/dev/flow-typed
|
||||
|
||||
[lints]
|
||||
all=warn
|
||||
|
||||
[options]
|
||||
include_warnings=true
|
||||
module.name_mapper='^@polkadot/api-\(format\|jsonrpc\|provider\|rx\)\(.*\)$' -> '<PROJECT_ROOT>/packages/api-\1/src\2'
|
||||
module.name_mapper='^@polkadot/api\(.*\)$' -> '<PROJECT_ROOT>/packages/api/src\1'
|
||||
+1
-1
@@ -10,5 +10,5 @@
|
||||
"packages": [
|
||||
"packages/*"
|
||||
],
|
||||
"version": "0.13.8"
|
||||
"version": "0.14.0"
|
||||
}
|
||||
|
||||
+4
-3
@@ -9,13 +9,14 @@
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "polkadot-dev-build-babel",
|
||||
"check": "eslint packages && flow check",
|
||||
"build": "polkadot-dev-build-ts",
|
||||
"check": "tsc --noEmit",
|
||||
"clean": "polkadot-dev-clean-build",
|
||||
"postinstall": "polkadot-dev-yarn-only",
|
||||
"test": "jest --coverage"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/dev": "^0.19.25"
|
||||
"@polkadot/dev": "^0.20.2",
|
||||
"@polkadot/ts": "^0.0.18"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-format",
|
||||
"version": "0.13.8",
|
||||
"version": "0.14.0",
|
||||
"description": "Input/Output formatters for JsonRPC exchange",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -35,9 +35,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.0.0-beta.47",
|
||||
"@polkadot/jsonrpc": "^0.17.24",
|
||||
"@polkadot/primitives-json": "^0.17.24",
|
||||
"@polkadot/util": "^0.22.9",
|
||||
"@polkadot/util-keyring": "^0.22.9"
|
||||
"@polkadot/jsonrpc": "^0.19.1",
|
||||
"@polkadot/primitives-json": "^0.19.1",
|
||||
"@polkadot/util": "^0.24.1",
|
||||
"@polkadot/util-keyring": "^0.24.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const echo = require('./echo');
|
||||
import echo from './echo';
|
||||
|
||||
describe('echo', () => {
|
||||
it('returns input value as output value', () => {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
module.exports = function echo (value: mixed): mixed {
|
||||
export default function echo (value: any): any {
|
||||
return value;
|
||||
};
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const format = require('./format');
|
||||
const echo = require('./echo');
|
||||
import format from './format';
|
||||
import echo from './echo';
|
||||
|
||||
describe('format', () => {
|
||||
let formatters;
|
||||
@@ -14,12 +14,12 @@ describe('format', () => {
|
||||
echoSpy = jest.fn(echo);
|
||||
warnSpy = jest.spyOn(console, 'warn');
|
||||
|
||||
formatters = {
|
||||
'Address': echoSpy,
|
||||
'Exception': () => {
|
||||
formatters = new Map([
|
||||
['Address', echoSpy],
|
||||
['Exception', () => {
|
||||
throw new Error('something went wrong');
|
||||
}
|
||||
};
|
||||
}]
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { Param$Types, Param$Type$Array } from '@polkadot/params/types';
|
||||
import type { FormatterFunction } from './types';
|
||||
import { Param$Types, Param$Type$Array } from '@polkadot/params/types';
|
||||
import { FormattersFunctionMap } from './types';
|
||||
|
||||
type FormattersFunctionMap = $Shape<{
|
||||
[Param$Types]: FormatterFunction
|
||||
}>;
|
||||
import typeToString from '@polkadot/params/typeToString';
|
||||
import isUndefined from '@polkadot/util/is/undefined';
|
||||
import logger from '@polkadot/util/logger';
|
||||
|
||||
const typeToString = require('@polkadot/params/typeToString');
|
||||
const isUndefined = require('@polkadot/util/is/undefined');
|
||||
const l = require('@polkadot/util/logger')('api-format');
|
||||
import echo from './echo';
|
||||
|
||||
const echo = require('./echo');
|
||||
const l = logger('api-format');
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
function formatSingleType (formatters: FormattersFunctionMap, type: Param$Types, value: any): any {
|
||||
const formatter: FormatterFunction = formatters[type];
|
||||
const formatter = formatters.get(type);
|
||||
|
||||
if (isUndefined(formatter)) {
|
||||
l.warn(`Unable to find default formatter for '${typeToString(type)}', falling back to echo`);
|
||||
@@ -33,16 +29,14 @@ function formatSingleType (formatters: FormattersFunctionMap, type: Param$Types,
|
||||
}
|
||||
}
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
function formatArrayType (formatters: FormattersFunctionMap, [ type ]: Param$Type$Array, value: Array<any>): any {
|
||||
return value.map((value) => {
|
||||
return formatSingleType(formatters, type, value);
|
||||
});
|
||||
}
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
module.exports = function format (formatters: FormattersFunctionMap, types: Array<Param$Types>, values: Array<any>): Array<any> {
|
||||
return values.map((value, index): mixed => {
|
||||
export default function format (formatters: FormattersFunctionMap, types: Array<Param$Types>, values: Array<any>): Array<any> {
|
||||
return values.map((value, index): any => {
|
||||
const type = types[index];
|
||||
|
||||
if (Array.isArray(type)) {
|
||||
@@ -52,4 +46,4 @@ module.exports = function format (formatters: FormattersFunctionMap, types: Arra
|
||||
|
||||
return formatSingleType(formatters, type, value);
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
const formatInputs = require('./input');
|
||||
const formatOutput = require('./output');
|
||||
import formatInputs from './input';
|
||||
import formatOutput from './output';
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
formatInputs,
|
||||
formatOutput
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { Params } from '@polkadot/params/types';
|
||||
|
||||
const addressDecode = require('@polkadot/util-keyring/address/decode');
|
||||
const bytesEncode = require('@polkadot/primitives-json/bytes/encode');
|
||||
const hashEncode = require('@polkadot/primitives-json/hash/encode');
|
||||
|
||||
const format = require('./format');
|
||||
|
||||
const formatters = {
|
||||
// funnily named, goes from address -> u8a
|
||||
'AccountId': addressDecode,
|
||||
'Bytes': bytesEncode,
|
||||
'Hash': hashEncode
|
||||
};
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
module.exports = function formatInputs (params: Params, values: Array<any>): Array<any> {
|
||||
const types = params.map(({ type }) => type);
|
||||
|
||||
return format(formatters, types, values);
|
||||
};
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { formatInputs } = require('./index');
|
||||
import { formatInputs } from './index';
|
||||
|
||||
describe('formatInputs', () => {
|
||||
it('formats each value in an array', () => {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { Params, Param$Types } from '@polkadot/params/types';
|
||||
import { FormatterFunction } from './types';
|
||||
|
||||
import addressDecode from '@polkadot/util-keyring/address/decode';
|
||||
import bytesEncode from '@polkadot/primitives-json/bytes/encode';
|
||||
import hashEncode from '@polkadot/primitives-json/hash/encode';
|
||||
|
||||
import format from './format';
|
||||
|
||||
const formatters = new Map<Param$Types, FormatterFunction>([
|
||||
// funnily named, goes from address -> u8a
|
||||
['AccountId', addressDecode],
|
||||
['Bytes', bytesEncode],
|
||||
['Hash', hashEncode]
|
||||
]);
|
||||
|
||||
export default function formatInputs (params: Params, values: Array<any>): Array<any> {
|
||||
const types = params.map(({ type }) => type);
|
||||
|
||||
return format(formatters, types, values);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { Param$Types } from '@polkadot/params/types';
|
||||
|
||||
const addressEncode = require('@polkadot/util-keyring/address/encode');
|
||||
const bnDecode = require('@polkadot/primitives-json/bn/decode');
|
||||
const bytesDecode = require('@polkadot/primitives-json/bytes/decode');
|
||||
const headerDecode = require('@polkadot/primitives-json/header/decode');
|
||||
const isNull = require('@polkadot/util/is/null');
|
||||
const isUndefined = require('@polkadot/util/is/undefined');
|
||||
|
||||
const format = require('./format');
|
||||
|
||||
const formatters = {
|
||||
// publicKey -> address
|
||||
'AccountId': addressEncode,
|
||||
'BlockNumber': bnDecode,
|
||||
'Bytes': bytesDecode,
|
||||
'Header': headerDecode,
|
||||
'u64': bnDecode
|
||||
};
|
||||
|
||||
module.exports = function formatOutput (type: Param$Types, value?: mixed): ?mixed {
|
||||
if (isUndefined(value) || isNull(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return format(formatters, [type], [value])[0];
|
||||
};
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const BN = require('bn.js');
|
||||
import BN from 'bn.js';
|
||||
|
||||
const { formatOutput } = require('./index');
|
||||
import { formatOutput } from './index';
|
||||
|
||||
describe('formatOutput', () => {
|
||||
it('formats the value', () => {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { Param$Types } from '@polkadot/params/types';
|
||||
import { FormatterFunction } from './types';
|
||||
|
||||
import addressEncode from '@polkadot/util-keyring/address/encode';
|
||||
import bnDecode from '@polkadot/primitives-json/bn/decode';
|
||||
import bytesDecode from '@polkadot/primitives-json/bytes/decode';
|
||||
import headerDecode from '@polkadot/primitives-json/header/decode';
|
||||
import isNull from '@polkadot/util/is/null';
|
||||
import isUndefined from '@polkadot/util/is/undefined';
|
||||
|
||||
import format from './format';
|
||||
|
||||
const formatters = new Map<Param$Types, FormatterFunction>([
|
||||
// publicKey -> address
|
||||
['AccountId', addressEncode],
|
||||
['BlockNumber', bnDecode],
|
||||
['Bytes', bytesDecode],
|
||||
['Header', headerDecode],
|
||||
['u64', bnDecode]
|
||||
]);
|
||||
|
||||
export default function formatOutput (type: Param$Types, value?: any): any | null {
|
||||
if (isUndefined(value) || isNull(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return format(formatters, [type], [value])[0];
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/api-format authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
export type FormatterFunction = (value: any) => mixed;
|
||||
import { Param$Types } from '@polkadot/params/types';
|
||||
|
||||
export type FormatterFunction = (value: any) => any;
|
||||
|
||||
type FormattersFunctionMap = Map<Param$Types, FormatterFunction>;
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-provider",
|
||||
"version": "0.13.8",
|
||||
"version": "0.14.0",
|
||||
"description": "Transport providers for the API",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -39,10 +39,11 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.0.0-beta.47",
|
||||
"@polkadot/storage": "^0.17.24",
|
||||
"@polkadot/util": "^0.22.9",
|
||||
"@polkadot/util-crypto": "^0.22.9",
|
||||
"@polkadot/util-keyring": "^0.22.9",
|
||||
"@polkadot/storage": "^0.19.1",
|
||||
"@polkadot/util": "^0.24.1",
|
||||
"@polkadot/util-crypto": "^0.24.1",
|
||||
"@polkadot/util-keyring": "^0.24.1",
|
||||
"@types/nock": "^9.1.3",
|
||||
"eventemitter3": "^2.0.3",
|
||||
"isomorphic-fetch": "^2.2.1",
|
||||
"websocket": "^1.0.25"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const createCoder = require('./index');
|
||||
import createCoder from './index';
|
||||
|
||||
describe('decodeResponse', () => {
|
||||
let coder;
|
||||
|
||||
+7
-8
@@ -1,14 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcResponse, JsonRpcResponseBase$Error } from '../../types';
|
||||
import type { RpcCoderState } from './types';
|
||||
import { JsonRpcResponse, JsonRpcResponseBase$Error } from '../../types';
|
||||
import { RpcCoderState } from './types';
|
||||
|
||||
const assert = require('@polkadot/util/assert');
|
||||
const isNumber = require('@polkadot/util/is/number');
|
||||
const isUndefined = require('@polkadot/util/is/undefined');
|
||||
import assert from '@polkadot/util/assert';
|
||||
import isNumber from '@polkadot/util/is/number';
|
||||
import isUndefined from '@polkadot/util/is/undefined';
|
||||
|
||||
function checkError (error?: JsonRpcResponseBase$Error) {
|
||||
if (!error) {
|
||||
@@ -20,7 +19,7 @@ function checkError (error?: JsonRpcResponseBase$Error) {
|
||||
throw new Error(`[${code}]: ${message}`);
|
||||
}
|
||||
|
||||
module.exports = function decodeResponse (self: RpcCoderState, response: JsonRpcResponse): mixed {
|
||||
export default function decodeResponse (self: RpcCoderState, response: JsonRpcResponse): any {
|
||||
assert(response, 'Empty response object received');
|
||||
assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object');
|
||||
|
||||
@@ -39,4 +38,4 @@ module.exports = function decodeResponse (self: RpcCoderState, response: JsonRpc
|
||||
}
|
||||
|
||||
return response.result;
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const createCoder = require('./index');
|
||||
import createCoder from './index';
|
||||
|
||||
describe('encodeJson', () => {
|
||||
let coder;
|
||||
|
||||
+4
-5
@@ -1,14 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { RpcCoderState } from './types';
|
||||
import { RpcCoderState } from './types';
|
||||
|
||||
const encodeObject = require('./encodeObject');
|
||||
import encodeObject from './encodeObject';
|
||||
|
||||
module.exports = function encodeJson (self: RpcCoderState, method: string, params: Array<mixed>): string {
|
||||
export default function encodeJson (self: RpcCoderState, method: string, params: Array<any>): string {
|
||||
return JSON.stringify(
|
||||
encodeObject(self, method, params)
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const createCoder = require('./index');
|
||||
import createCoder from './index';
|
||||
|
||||
describe('encodeObject', () => {
|
||||
let coder;
|
||||
|
||||
+4
-5
@@ -1,16 +1,15 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcRequest } from '../../types';
|
||||
import type { RpcCoderState } from './types';
|
||||
import { JsonRpcRequest } from '../../types';
|
||||
import { RpcCoderState } from './types';
|
||||
|
||||
module.exports = function encodeObject (self: RpcCoderState, method: string, params: Array<mixed>): JsonRpcRequest {
|
||||
export default function encodeObject (self: RpcCoderState, method: string, params: Array<any>): JsonRpcRequest {
|
||||
return {
|
||||
id: ++self.id,
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcRequest, JsonRpcResponse } from '../../types';
|
||||
import type { RpcCoder, RpcCoderState } from './types';
|
||||
|
||||
const decodeResponse = require('./decodeResponse');
|
||||
const encodeJson = require('./encodeJson');
|
||||
const encodeObject = require('./encodeObject');
|
||||
|
||||
module.exports = function rpcCoder (): RpcCoder {
|
||||
const self: RpcCoderState = {
|
||||
id: 0
|
||||
};
|
||||
|
||||
return {
|
||||
decodeResponse: (response: JsonRpcResponse): mixed =>
|
||||
decodeResponse(self, response),
|
||||
encodeJson: (method: string, params: Array<mixed>): string =>
|
||||
encodeJson(self, method, params),
|
||||
encodeObject: (method: string, params: Array<mixed>): JsonRpcRequest =>
|
||||
encodeObject(self, method, params),
|
||||
getId: (): number =>
|
||||
self.id
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { JsonRpcRequest, JsonRpcResponse } from '../../types';
|
||||
import { RpcCoder, RpcCoderState } from './types';
|
||||
|
||||
import decodeResponse from './decodeResponse';
|
||||
import encodeJson from './encodeJson';
|
||||
import encodeObject from './encodeObject';
|
||||
|
||||
export default function rpcCoder (): RpcCoder {
|
||||
const self: RpcCoderState = {
|
||||
id: 0
|
||||
};
|
||||
|
||||
return {
|
||||
decodeResponse: (response: JsonRpcResponse): any =>
|
||||
decodeResponse(self, response),
|
||||
encodeJson: (method: string, params: Array<any>): string =>
|
||||
encodeJson(self, method, params),
|
||||
encodeObject: (method: string, params: Array<any>): JsonRpcRequest =>
|
||||
encodeObject(self, method, params),
|
||||
getId: (): number =>
|
||||
self.id
|
||||
};
|
||||
}
|
||||
Vendored
+4
-5
@@ -1,14 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcRequest, JsonRpcResponse } from '../../types';
|
||||
import { JsonRpcRequest, JsonRpcResponse } from '../../types';
|
||||
|
||||
export type RpcCoder = {
|
||||
decodeResponse: (response: JsonRpcResponse) => mixed,
|
||||
encodeObject: (method: string, params: Array<mixed>) => JsonRpcRequest,
|
||||
encodeJson: (method: string, params: Array<mixed>) => string,
|
||||
decodeResponse: (response: JsonRpcResponse) => any,
|
||||
encodeObject: (method: string, params: Array<any>) => JsonRpcRequest,
|
||||
encodeJson: (method: string, params: Array<any>) => string,
|
||||
getId: () => number
|
||||
};
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
|
||||
require('./polyfill');
|
||||
|
||||
const on = require('./on');
|
||||
const send = require('./send');
|
||||
const subscribe = require('./subscribe');
|
||||
const state = require('./state');
|
||||
const unsubscribe = require('./unsubscribe');
|
||||
|
||||
module.exports = function httpProvider (endpoint: string): ProviderInterface {
|
||||
const self = state(endpoint);
|
||||
|
||||
return {
|
||||
isConnected: (): boolean =>
|
||||
true,
|
||||
on: (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void =>
|
||||
on(self, type, sub),
|
||||
send: (method: string, params: Array<mixed>): Promise<mixed> =>
|
||||
send(self, method, params),
|
||||
subscribe: (method: string, params: Array<mixed>, cb: ProviderInterface$Callback): Promise<number> =>
|
||||
subscribe(self, method, params, cb),
|
||||
unsubscribe: (method: string, id: number): Promise<boolean> =>
|
||||
unsubscribe(self, method, id)
|
||||
};
|
||||
};
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { TEST_HTTP_URL } = require('../../test/mockHttp');
|
||||
import { TEST_HTTP_URL } from '../../test/mockHttp';
|
||||
|
||||
const createHttp = require('./index');
|
||||
import createHttp from './index';
|
||||
|
||||
describe('Http', () => {
|
||||
let http;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
|
||||
import './polyfill';
|
||||
|
||||
import on from './on';
|
||||
import send from './send';
|
||||
import subscribe from './subscribe';
|
||||
import state from './state';
|
||||
import unsubscribe from './unsubscribe';
|
||||
|
||||
export default function httpProvider (endpoint: string): ProviderInterface {
|
||||
const self = state(endpoint);
|
||||
|
||||
return {
|
||||
isConnected: (): boolean =>
|
||||
true,
|
||||
on: (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void =>
|
||||
on(self, type, sub),
|
||||
send: (method: string, params: Array<any>): Promise<any> =>
|
||||
send(self, method, params),
|
||||
subscribe: (method: string, params: Array<any>, cb: ProviderInterface$Callback): Promise<number> =>
|
||||
subscribe(self, method, params, cb),
|
||||
unsubscribe: (method: string, id: number): Promise<boolean> =>
|
||||
unsubscribe(self, method, id)
|
||||
};
|
||||
};
|
||||
@@ -1,11 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import type { HttpState } from './types';
|
||||
import { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { HttpState } from './types';
|
||||
|
||||
module.exports = function on (self: HttpState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
export default function on (self: HttpState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
self.l.error(`Provider does not have 'on' emitters for type '${type}'`);
|
||||
};
|
||||
}
|
||||
-1
@@ -1,7 +1,6 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
if (typeof fetch === 'undefined') {
|
||||
require('isomorphic-fetch');
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { mockHttp, TEST_HTTP_URL } = require('../../test/mockHttp');
|
||||
import { mockHttp, TEST_HTTP_URL } from '../../test/mockHttp';
|
||||
|
||||
const createHttp = require('./index');
|
||||
import createHttp from './index';
|
||||
|
||||
describe('send', () => {
|
||||
let http;
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { HttpState } from './types';
|
||||
import { HttpState } from './types';
|
||||
|
||||
const assert = require('@polkadot/util/assert');
|
||||
import assert from '@polkadot/util/assert';
|
||||
|
||||
module.exports = async function send ({ coder, endpoint }: HttpState, method: string, params: Array<mixed>): Promise<mixed> {
|
||||
export default async function send ({ coder, endpoint }: HttpState, method: string, params: Array<any>): Promise<any> {
|
||||
const body = coder.encodeJson(method, params);
|
||||
const response = await fetch(endpoint, {
|
||||
body,
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const state = require('./state');
|
||||
import state from './state';
|
||||
|
||||
describe('state', () => {
|
||||
it('requires an http:// prefixed endpoint', () => {
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { HttpState } from './types';
|
||||
import { HttpState } from './types';
|
||||
|
||||
const assert = require('@polkadot/util/assert');
|
||||
const l = require('@polkadot/util/logger')('api-http');
|
||||
import assert from '@polkadot/util/assert';
|
||||
import logger from '@polkadot/util/logger';
|
||||
|
||||
const coder = require('../coder/json');
|
||||
import coder from '../coder/json';
|
||||
|
||||
module.exports = function state (endpoint: string): HttpState {
|
||||
const l = logger('api-http');
|
||||
|
||||
export default function state (endpoint: string): HttpState {
|
||||
assert(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`);
|
||||
|
||||
return {
|
||||
@@ -18,4 +19,4 @@ module.exports = function state (endpoint: string): HttpState {
|
||||
endpoint,
|
||||
l
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface$Callback } from '../types';
|
||||
import type { HttpState } from './types';
|
||||
|
||||
module.exports = async function subscribe (self: HttpState, method: string, params: Array<mixed>, cb: ProviderInterface$Callback): Promise<number> {
|
||||
throw new Error('Subscriptions has not been implemented');
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface$Callback } from '../types';
|
||||
import { HttpState } from './types';
|
||||
|
||||
export default async function subscribe (self: HttpState, method: string, params: Array<any>, cb: ProviderInterface$Callback): Promise<number> {
|
||||
throw new Error('Subscriptions has not been implemented');
|
||||
};
|
||||
+2
-3
@@ -1,10 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { Logger } from '@polkadot/util/types';
|
||||
import type { RpcCoder } from '../coder/json/types';
|
||||
import { Logger } from '@polkadot/util/types';
|
||||
import { RpcCoder } from '../coder/json/types';
|
||||
|
||||
export type HttpState = {
|
||||
coder: RpcCoder,
|
||||
+3
-4
@@ -1,10 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { HttpState } from './types';
|
||||
import { HttpState } from './types';
|
||||
|
||||
module.exports = async function unsubscribe (self: HttpState, method: string, id: number): Promise<boolean> {
|
||||
export default async function unsubscribe (self: HttpState, method: string, id: number): Promise<boolean> {
|
||||
throw new Error('Subscriptions has not been implemented');
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
const http = require('./http');
|
||||
const ws = require('./ws');
|
||||
import http from './http';
|
||||
import ws from './ws';
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
http,
|
||||
ws
|
||||
};
|
||||
@@ -1,18 +1,17 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { ProviderInterface, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
|
||||
const mocks = require('./mocks');
|
||||
const on = require('./on');
|
||||
const send = require('./send');
|
||||
const state = require('./state');
|
||||
const subscribe = require('./subscribe');
|
||||
const unsubscribe = require('./unsubscribe');
|
||||
import mocks from './mocks';
|
||||
import on from './on';
|
||||
import send from './send';
|
||||
import state from './state';
|
||||
import subscribe from './subscribe';
|
||||
import unsubscribe from './unsubscribe';
|
||||
|
||||
module.exports = function mockProvider (): ProviderInterface {
|
||||
export default function mockProvider (): ProviderInterface {
|
||||
const self = state();
|
||||
|
||||
mocks(self);
|
||||
@@ -22,11 +21,11 @@ module.exports = function mockProvider (): ProviderInterface {
|
||||
true,
|
||||
on: (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void =>
|
||||
on(self, type, sub),
|
||||
send: (method: string, params: Array<mixed>): Promise<mixed> =>
|
||||
send: (method: string, params: Array<any>): Promise<any> =>
|
||||
send(self, method, params),
|
||||
subscribe: (method: string, ...params: Array<mixed>): Promise<number> =>
|
||||
subscribe: (method: string, ...params: Array<any>): Promise<number> =>
|
||||
subscribe(self, method, params),
|
||||
unsubscribe: (method: string, id: number): Promise<boolean> =>
|
||||
unsubscribe(self, method, id)
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
// FIME: This file is way too long and way too messy
|
||||
|
||||
import type { Storage$Key } from '@polkadot/storage/types';
|
||||
import type { KeyringPair } from '@polkadot/util-keyring/types';
|
||||
import type { ProviderInterface$Emitted } from '../types';
|
||||
import type { MockState, MockState$Subscription$Callback } from './types';
|
||||
|
||||
const BN = require('bn.js');
|
||||
const headerEncode = require('@polkadot/primitives-json/header/encode');
|
||||
const createKey = require('@polkadot/storage/key');
|
||||
const state = require('@polkadot/storage');
|
||||
const bnToU8a = require('@polkadot/util/bn/toU8a');
|
||||
const u8aToHex = require('@polkadot/util/u8a/toHex');
|
||||
const randomAsU8a = require('@polkadot/util-crypto/random/asU8a');
|
||||
const testKeyring = require('@polkadot/util-keyring/testing');
|
||||
|
||||
const keyring = testKeyring();
|
||||
|
||||
const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
|
||||
let emitIndex = 0;
|
||||
|
||||
function makeBlockHeader (prevNumber: BN) {
|
||||
const blockNumber = prevNumber.addn(1);
|
||||
|
||||
return {
|
||||
digest: {
|
||||
logs: []
|
||||
},
|
||||
extrinsicsRoot: randomAsU8a(),
|
||||
number: blockNumber,
|
||||
parentHash: prevNumber.eqn(-1)
|
||||
? new Uint8Array(32)
|
||||
: bnToU8a(prevNumber, 256),
|
||||
stateRoot: bnToU8a(blockNumber, 256)
|
||||
};
|
||||
}
|
||||
|
||||
function updateSubs (subscriptions, method, value) {
|
||||
subscriptions[method].lastValue = value;
|
||||
|
||||
Object
|
||||
.values(subscriptions[method].callbacks)
|
||||
.forEach((cb) => {
|
||||
try {
|
||||
// flowlint-next-line unclear-type:off
|
||||
((cb: any): MockState$Subscription$Callback)(null, value);
|
||||
} catch (error) {
|
||||
console.error(`Error on '${method}' subscription`, error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setStorageBn (storage, key: Storage$Key, value: BN | number, ...keyParams: Array<Uint8Array>): void {
|
||||
const keyValue = u8aToHex(
|
||||
createKey(key).apply(null, keyParams)
|
||||
);
|
||||
|
||||
storage[keyValue] = bnToU8a(value, 64, true);
|
||||
}
|
||||
|
||||
module.exports = function mocks ({ emitter, storage, subscriptions }: MockState): void {
|
||||
let newHead = makeBlockHeader(new BN(-1));
|
||||
|
||||
setInterval(() => {
|
||||
if (++emitIndex === emitEvents.length) {
|
||||
emitIndex = 0;
|
||||
}
|
||||
|
||||
emitter.emit(emitEvents[emitIndex]);
|
||||
|
||||
newHead = makeBlockHeader(newHead.number);
|
||||
|
||||
keyring.getPairs().forEach(({ publicKey }: KeyringPair, index: number) => {
|
||||
setStorageBn(storage, state.staking.public.freeBalanceOf, newHead.number.muln(3).iaddn(index), publicKey());
|
||||
setStorageBn(storage, state.system.public.accountIndexOf, newHead.number.addn(index), publicKey());
|
||||
});
|
||||
|
||||
setStorageBn(storage, state.timestamp.public.current, Math.floor(Date.now() / 1000));
|
||||
|
||||
updateSubs(subscriptions, 'subscribe_newHead', headerEncode(newHead));
|
||||
}, 5000);
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
// FIME: This file is way too long and way too messy
|
||||
|
||||
import { Storage$Key } from '@polkadot/storage/types';
|
||||
import { KeyringPair } from '@polkadot/util-keyring/types';
|
||||
import { ProviderInterface$Emitted } from '../types';
|
||||
import { MockState, MockState$Storage, MockState$Subscriptions, MockState$Subscription$Callback } from './types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import headerEncode from '@polkadot/primitives-json/header/encode';
|
||||
import createKey from '@polkadot/storage/key';
|
||||
import state from '@polkadot/storage';
|
||||
import bnToU8a from '@polkadot/util/bn/toU8a';
|
||||
import u8aToHex from '@polkadot/util/u8a/toHex';
|
||||
import randomAsU8a from '@polkadot/util-crypto/random/asU8a';
|
||||
import testKeyring from '@polkadot/util-keyring/testing';
|
||||
|
||||
const keyring = testKeyring();
|
||||
// @ts-ignore yes, it _should_ be there
|
||||
const stateStaking = state.get('staking').public;
|
||||
// @ts-ignore yes, it _should_ be there
|
||||
const stateSystem = state.get('staking').public;
|
||||
// @ts-ignore yes, it _should_ be there
|
||||
const stateTimestamp = state.get('timestamp').public;
|
||||
|
||||
const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
|
||||
let emitIndex = 0;
|
||||
|
||||
function makeBlockHeader (prevNumber: BN) {
|
||||
const blockNumber = prevNumber.addn(1);
|
||||
|
||||
return {
|
||||
digest: {
|
||||
logs: []
|
||||
},
|
||||
extrinsicsRoot: randomAsU8a(),
|
||||
number: blockNumber,
|
||||
parentHash: prevNumber.eqn(-1)
|
||||
? new Uint8Array(32)
|
||||
: bnToU8a(prevNumber, 256),
|
||||
stateRoot: bnToU8a(blockNumber, 256)
|
||||
};
|
||||
}
|
||||
|
||||
function updateSubs (subscriptions: MockState$Subscriptions, method: string, value: any) {
|
||||
subscriptions[method].lastValue = value;
|
||||
|
||||
Object
|
||||
.values(subscriptions[method].callbacks)
|
||||
.forEach((cb) => {
|
||||
try {
|
||||
(cb as MockState$Subscription$Callback)(null, value);
|
||||
} catch (error) {
|
||||
console.error(`Error on '${method}' subscription`, error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setStorageBn (storage: MockState$Storage, key: Storage$Key, value: BN | number, ...keyParams: Array<Uint8Array>): void {
|
||||
const keyValue = u8aToHex(
|
||||
createKey(key).apply(null, keyParams)
|
||||
);
|
||||
|
||||
storage[keyValue] = bnToU8a(value, 64, true);
|
||||
}
|
||||
|
||||
export default function mocks ({ emitter, storage, subscriptions }: MockState): void {
|
||||
let newHead = makeBlockHeader(new BN(-1));
|
||||
|
||||
setInterval(() => {
|
||||
if (++emitIndex === emitEvents.length) {
|
||||
emitIndex = 0;
|
||||
}
|
||||
|
||||
emitter.emit(emitEvents[emitIndex]);
|
||||
|
||||
newHead = makeBlockHeader(newHead.number);
|
||||
|
||||
keyring.getPairs().forEach(({ publicKey }: KeyringPair, index: number) => {
|
||||
setStorageBn(storage, stateStaking.freeBalanceOf, newHead.number.muln(3).iaddn(index), publicKey());
|
||||
setStorageBn(storage, stateSystem.accountIndexOf, newHead.number.addn(index), publicKey());
|
||||
});
|
||||
|
||||
setStorageBn(storage, stateTimestamp.current, Math.floor(Date.now() / 1000));
|
||||
|
||||
updateSubs(subscriptions, 'subscribe_newHead', headerEncode(newHead));
|
||||
}, 5000);
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import type { MockState } from './types';
|
||||
|
||||
module.exports = function on (self: MockState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
self.emitter.on(type, sub);
|
||||
};
|
||||
@@ -1,11 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import type { WsState } from './types';
|
||||
import { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { MockState } from './types';
|
||||
|
||||
module.exports = function on (self: WsState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
export default function on (self: MockState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
self.emitter.on(type, sub);
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { MockState } from './types';
|
||||
import { MockState } from './types';
|
||||
|
||||
module.exports = async function send ({ requests, storage }: MockState, method: string, params: Array<mixed>): Promise<mixed> {
|
||||
export default async function send ({ requests, storage }: MockState, method: string, params: Array<any>): Promise<any> {
|
||||
if (!requests[method]) {
|
||||
throw new Error(`provider.send: Invalid method '${method}'`);
|
||||
}
|
||||
|
||||
return requests[method](storage, params);
|
||||
};
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { MockState, MockState$Storage } from './types';
|
||||
|
||||
const EventEmitter = require('eventemitter3');
|
||||
const interfaces = require('@polkadot/jsonrpc');
|
||||
const u8aToHex = require('@polkadot/util/u8a/toHex');
|
||||
const l = require('@polkadot/util/logger')('api-mock');
|
||||
|
||||
const SUBSCRIPTIONS = Array.prototype.concat.apply(
|
||||
[], Object.keys(interfaces).map((section) => {
|
||||
return Object
|
||||
.keys(interfaces[section].public)
|
||||
.filter((method) => interfaces[section].public[method].isSubscription)
|
||||
.map((method) => `subscribe_${method}`);
|
||||
})
|
||||
);
|
||||
|
||||
const REQUESTS = {
|
||||
'state_getStorage': (storage: MockState$Storage, params: Array<mixed>): string => {
|
||||
return u8aToHex(
|
||||
// flowlint-next-line unclear-type:off
|
||||
storage[((params[0]: any): string)]
|
||||
);
|
||||
},
|
||||
'system_chain': (): string => 'mockChain',
|
||||
'system_name': (): string => 'mockClient',
|
||||
'system_version': (): string => '9.8.7'
|
||||
};
|
||||
|
||||
module.exports = function state (): MockState {
|
||||
const storage = {};
|
||||
const subscriptions = SUBSCRIPTIONS.reduce((subscriptions, name) => {
|
||||
subscriptions[name] = {
|
||||
callbacks: {},
|
||||
lastValue: null
|
||||
};
|
||||
|
||||
return subscriptions;
|
||||
}, {});
|
||||
|
||||
return {
|
||||
emitter: new EventEmitter(),
|
||||
l,
|
||||
requests: Object.assign({}, REQUESTS),
|
||||
storage,
|
||||
subscriptionId: 0,
|
||||
subscriptionMap: {},
|
||||
subscriptions
|
||||
};
|
||||
};
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const createState = require('./state');
|
||||
import createState from './state';
|
||||
|
||||
describe('state', () => {
|
||||
let state;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { MockState, MockState$Storage, MockState$Subscriptions } from './types';
|
||||
|
||||
import E3 from 'eventemitter3';
|
||||
import interfaces from '@polkadot/jsonrpc';
|
||||
import u8aToHex from '@polkadot/util/u8a/toHex';
|
||||
import logger from '@polkadot/util/logger';
|
||||
|
||||
const l =logger('api-mock');
|
||||
|
||||
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
|
||||
[], [...interfaces.values()].map((areas) =>
|
||||
Object
|
||||
.keys(areas.public)
|
||||
.filter((method) =>
|
||||
areas.public[method].isSubscription
|
||||
)
|
||||
.map((method) =>
|
||||
`subscribe_${method}`
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
const REQUESTS = {
|
||||
'state_getStorage': (storage: MockState$Storage, params: Array<any>): string => {
|
||||
return u8aToHex(
|
||||
storage[(params[0] as string)]
|
||||
);
|
||||
},
|
||||
'system_chain': (): string => 'mockChain',
|
||||
'system_name': (): string => 'mockClient',
|
||||
'system_version': (): string => '9.8.7'
|
||||
};
|
||||
|
||||
export default function state (): MockState {
|
||||
const storage = {};
|
||||
const subscriptions: MockState$Subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
|
||||
subs[name] = {
|
||||
callbacks: {},
|
||||
lastValue: null
|
||||
};
|
||||
|
||||
return subs;
|
||||
}, ({} as MockState$Subscriptions));
|
||||
|
||||
return {
|
||||
emitter: new E3.EventEmitter(),
|
||||
l,
|
||||
requests: Object.assign({}, REQUESTS),
|
||||
storage,
|
||||
subscriptionId: 0,
|
||||
subscriptionMap: {},
|
||||
subscriptions
|
||||
};
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const createState = require('./state');
|
||||
const subscribe = require('./subscribe');
|
||||
import createState from './state';
|
||||
import subscribe from './subscribe';
|
||||
|
||||
describe('subscribe', () => {
|
||||
let state;
|
||||
|
||||
+4
-6
@@ -1,16 +1,14 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { MockState, MockState$Subscription$Callback } from './types';
|
||||
import { MockState, MockState$Subscription$Callback } from './types';
|
||||
|
||||
module.exports = async function subscribe (self: MockState, method: string, params: Array<mixed>): Promise<number> {
|
||||
export default async function subscribe (self: MockState, method: string, params: Array<any>): Promise<number> {
|
||||
self.l.debug(() => ['subscribe', method, params]);
|
||||
|
||||
if (self.subscriptions[method]) {
|
||||
// flowlint-next-line unclear-type:off
|
||||
const callback = ((params.pop(): any): MockState$Subscription$Callback);
|
||||
const callback: MockState$Subscription$Callback = params.pop();
|
||||
const id = ++self.subscriptionId;
|
||||
|
||||
self.subscriptions[method].callbacks[id] = callback;
|
||||
@@ -22,4 +20,4 @@ module.exports = async function subscribe (self: MockState, method: string, para
|
||||
}
|
||||
|
||||
throw new Error(`provider.subscribe: Invalid method '${method}'`);
|
||||
};
|
||||
}
|
||||
+10
-11
@@ -1,38 +1,37 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type EventEmitter from 'eventemitter3';
|
||||
import type { Logger } from '@polkadot/util/types';
|
||||
import E3 from 'eventemitter3';
|
||||
import { Logger } from '@polkadot/util/types';
|
||||
|
||||
export type MockState$Subscription$Callback = (error: ?Error, value: mixed) => void;
|
||||
export type MockState$Subscription$Callback = (error: Error | null, value: any) => void;
|
||||
|
||||
export type MockState$Subscriptions = {
|
||||
[string]: {
|
||||
[index: string]: {
|
||||
callbacks: {
|
||||
[number]: MockState$Subscription$Callback
|
||||
[index: number]: MockState$Subscription$Callback
|
||||
},
|
||||
lastValue: mixed
|
||||
lastValue: any
|
||||
}
|
||||
};
|
||||
|
||||
export type MockState$Storage = {
|
||||
[string]: Uint8Array
|
||||
[index: string]: Uint8Array
|
||||
};
|
||||
|
||||
export type MockState$Requests = {
|
||||
[string]: (storage: MockState$Storage, params: Array<mixed>) => string
|
||||
[index: string]: (storage: MockState$Storage, params: Array<any>) => string
|
||||
};
|
||||
|
||||
export type MockState = {
|
||||
emitter: EventEmitter,
|
||||
emitter: E3.EventEmitter,
|
||||
l: Logger,
|
||||
requests: MockState$Requests,
|
||||
storage: MockState$Storage,
|
||||
subscriptionId: number,
|
||||
subscriptionMap: {
|
||||
[number]: string
|
||||
[index: number]: string
|
||||
},
|
||||
subscriptions: MockState$Subscriptions
|
||||
};
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const createState = require('./state');
|
||||
const subscribe = require('./subscribe');
|
||||
const unsubscribe = require('./unsubscribe');
|
||||
import createState from './state';
|
||||
import subscribe from './subscribe';
|
||||
import unsubscribe from './unsubscribe';
|
||||
|
||||
describe('unsubscribe', () => {
|
||||
let state;
|
||||
|
||||
+3
-4
@@ -1,11 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { MockState } from './types';
|
||||
import { MockState } from './types';
|
||||
|
||||
module.exports = async function unsubscribe (self: MockState, _: string, id: number): Promise<boolean> {
|
||||
export default async function unsubscribe (self: MockState, _: string, id: number): Promise<boolean> {
|
||||
const method = self.subscriptionMap[id];
|
||||
|
||||
self.l.debug(() => ['unsubscribe', id, method]);
|
||||
@@ -18,4 +17,4 @@ module.exports = async function unsubscribe (self: MockState, _: string, id: num
|
||||
delete self.subscriptions[method].callbacks[id];
|
||||
|
||||
return true;
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
export type JsonRpcObject = {
|
||||
id: number;
|
||||
@@ -10,7 +9,7 @@ export type JsonRpcObject = {
|
||||
|
||||
export type JsonRpcRequest = JsonRpcObject & {
|
||||
method: string;
|
||||
params: Array<mixed>;
|
||||
params: Array<any>;
|
||||
};
|
||||
|
||||
export type JsonRpcResponseBase$Error = {
|
||||
@@ -20,14 +19,14 @@ export type JsonRpcResponseBase$Error = {
|
||||
|
||||
type JsonRpcResponse$Single = {
|
||||
error?: JsonRpcResponseBase$Error;
|
||||
result?: mixed;
|
||||
result?: any;
|
||||
};
|
||||
|
||||
type JsonRpcResponse$Subscription = {
|
||||
method?: string;
|
||||
params: {
|
||||
error?: JsonRpcResponseBase$Error;
|
||||
result: mixed;
|
||||
result: any;
|
||||
subscription: number;
|
||||
}
|
||||
};
|
||||
@@ -36,17 +35,16 @@ export type JsonRpcResponseBase = JsonRpcResponse$Single & JsonRpcResponse$Subsc
|
||||
|
||||
export type JsonRpcResponse = JsonRpcObject & JsonRpcResponseBase;
|
||||
|
||||
export type ProviderInterface$Callback = (error: ?Error, result: mixed) => void;
|
||||
export type ProviderInterface$Callback = (error: Error | null, result: any) => void;
|
||||
|
||||
export type ProviderInterface$Emitted = 'connected' | 'disconnected';
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
export type ProviderInterface$EmitCb = (value?: any) => any;
|
||||
|
||||
export type ProviderInterface = {
|
||||
isConnected (): boolean,
|
||||
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void,
|
||||
send (method: string, params: Array<mixed>): Promise<mixed>,
|
||||
subscribe (method: string, params: Array<mixed>, cb: ProviderInterface$Callback): Promise<number>,
|
||||
send (method: string, params: Array<any>): Promise<any>,
|
||||
subscribe (method: string, params: Array<any>, cb: ProviderInterface$Callback): Promise<number>,
|
||||
unsubscribe (method: string, id: number): Promise<boolean>
|
||||
}
|
||||
@@ -2,10 +2,10 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { mockWs, TEST_WS_URL } = require('../../test/mockWs');
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
const createState = require('./state');
|
||||
const connect = require('./connect');
|
||||
import createState from './state';
|
||||
import connect from './connect';
|
||||
|
||||
describe('onError', () => {
|
||||
let mock;
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { WsState } from './types';
|
||||
import { WsState } from './types';
|
||||
|
||||
const onClose = require('./onClose');
|
||||
const onError = require('./onError');
|
||||
const onMessage = require('./onMessage');
|
||||
const onOpen = require('./onOpen');
|
||||
import onClose from './onClose';
|
||||
import onError from './onError';
|
||||
import onMessage from './onMessage';
|
||||
import onOpen from './onOpen';
|
||||
|
||||
module.exports = function connect (self: WsState): void {
|
||||
export default function connect (self: WsState): void {
|
||||
self.websocket = new WebSocket(self.endpoint);
|
||||
|
||||
self.websocket.onclose = onClose(self);
|
||||
self.websocket.onerror = onError(self);
|
||||
self.websocket.onmessage = onMessage(self);
|
||||
self.websocket.onopen = onOpen(self);
|
||||
};
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { mockWs, TEST_WS_URL } = require('../../test/mockWs');
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
const create = require('./index');
|
||||
import create from './index';
|
||||
|
||||
let ws;
|
||||
let mock;
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
|
||||
require('./polyfill');
|
||||
import './polyfill';
|
||||
|
||||
const connect = require('./connect');
|
||||
const on = require('./on');
|
||||
const send = require('./send');
|
||||
const state = require('./state');
|
||||
const subscribe = require('./subscribe');
|
||||
const unsubscribe = require('./unsubscribe');
|
||||
import connect from './connect';
|
||||
import on from './on';
|
||||
import send from './send';
|
||||
import state from './state';
|
||||
import subscribe from './subscribe';
|
||||
import unsubscribe from './unsubscribe';
|
||||
|
||||
module.exports = function wsProvider (endpoint: string, autoConnect: boolean = true): ProviderInterface {
|
||||
type WSProviderInterface = ProviderInterface & {
|
||||
connect (): void
|
||||
}
|
||||
|
||||
export default function wsProvider (endpoint: string, autoConnect: boolean = true): WSProviderInterface {
|
||||
const self = state(endpoint, autoConnect);
|
||||
|
||||
if (autoConnect) {
|
||||
@@ -28,11 +31,11 @@ module.exports = function wsProvider (endpoint: string, autoConnect: boolean = t
|
||||
self.isConnected,
|
||||
on: (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void =>
|
||||
on(self, type, sub),
|
||||
send: (method: string, params: Array<mixed>): Promise<mixed> =>
|
||||
send: (method: string, params: Array<any>): Promise<any> =>
|
||||
send(self, method, params),
|
||||
subscribe: (method: string, params: Array<mixed>, cb: ProviderInterface$Callback): Promise<number> =>
|
||||
subscribe: (method: string, params: Array<any>, cb: ProviderInterface$Callback): Promise<number> =>
|
||||
subscribe(self, method, params, cb),
|
||||
unsubscribe: (method: string, id: number): Promise<boolean> =>
|
||||
unsubscribe(self, method, id)
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { WsState } from './types';
|
||||
|
||||
export default function on (self: WsState, type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
self.emitter.on(type, sub);
|
||||
};
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { TEST_WS_URL } = require('../../test/mockWs');
|
||||
import { TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
const createState = require('./state');
|
||||
import createState from './state';
|
||||
|
||||
describe('onClose', () => {
|
||||
let mockConnect;
|
||||
@@ -21,7 +21,7 @@ describe('onClose', () => {
|
||||
});
|
||||
|
||||
it('reconnects after delay', () => {
|
||||
require('./onClose')(createState(TEST_WS_URL, true))();
|
||||
require('./onClose').default(createState(TEST_WS_URL, true))();
|
||||
|
||||
expect(mockConnect).not.toHaveBeenCalled();
|
||||
|
||||
@@ -31,7 +31,7 @@ describe('onClose', () => {
|
||||
});
|
||||
|
||||
it('does not reconnect when autoConnect false', () => {
|
||||
require('./onClose')(createState(TEST_WS_URL, false))();
|
||||
require('./onClose').default(createState(TEST_WS_URL, false))();
|
||||
|
||||
expect(mockConnect).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { WsState } from './types';
|
||||
import { WsState } from './types';
|
||||
|
||||
module.exports = function onClose (self: WsState): () => void {
|
||||
export default function onClose (self: WsState): () => void {
|
||||
return (): void => {
|
||||
self.l.debug(() => ['disconnected from', self.endpoint]);
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const onError = require('./onError');
|
||||
const createState = require('./state');
|
||||
import onError from './onError';
|
||||
import createState from './state';
|
||||
|
||||
describe('onError', () => {
|
||||
let state;
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { WsState } from './types';
|
||||
import { WsState } from './types';
|
||||
|
||||
module.exports = function onError (self: WsState): (Event) => void {
|
||||
export default function onError (self: WsState): (event: Event) => void {
|
||||
return (error: Event): void => {
|
||||
self.l.error(error);
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcResponse } from '../types';
|
||||
import type { WsState } from './types';
|
||||
|
||||
const isUndefined = require('@polkadot/util/is/undefined');
|
||||
|
||||
const onMessageResult = require('./onMessageResult');
|
||||
const onMessageSubscribe = require('./onMessageSubscribe');
|
||||
|
||||
module.exports = function onMessage (self: WsState): (MessageEvent) => void {
|
||||
return (message: MessageEvent): void => {
|
||||
self.l.debug(() => ['received', message.data]);
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
const response: JsonRpcResponse = JSON.parse(((message.data: any): string));
|
||||
|
||||
return isUndefined(response.method)
|
||||
? onMessageResult(self, response)
|
||||
: onMessageSubscribe(self, response);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { JsonRpcResponse } from '../types';
|
||||
import { WsState } from './types';
|
||||
|
||||
import isUndefined from '@polkadot/util/is/undefined';
|
||||
|
||||
import onMessageResult from './onMessageResult';
|
||||
import onMessageSubscribe from './onMessageSubscribe';
|
||||
|
||||
export default function onMessage (self: WsState): (event: MessageEvent) => void {
|
||||
return (message: MessageEvent): void => {
|
||||
self.l.debug(() => ['received', message.data]);
|
||||
|
||||
const response: JsonRpcResponse = JSON.parse(message.data as string);
|
||||
|
||||
return isUndefined(response.method)
|
||||
? onMessageResult(self, response)
|
||||
: onMessageSubscribe(self, response);
|
||||
};
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const onMessage = require('./onMessage');
|
||||
const createState = require('./state');
|
||||
import onMessage from './onMessage';
|
||||
import createState from './state';
|
||||
|
||||
describe('onMessageResult', () => {
|
||||
let state;
|
||||
|
||||
+6
-8
@@ -1,12 +1,11 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcResponse } from '../types';
|
||||
import type { WsState } from './types';
|
||||
import { JsonRpcResponse } from '../types';
|
||||
import { WsState } from './types';
|
||||
|
||||
module.exports = function onMessageResult (self: WsState, response: JsonRpcResponse): void {
|
||||
export default function onMessageResult (self: WsState, response: JsonRpcResponse): void {
|
||||
self.l.debug(() => ['handling: response =', response, 'id =', response.id]);
|
||||
|
||||
const handler = self.handlers[response.id];
|
||||
@@ -21,16 +20,15 @@ module.exports = function onMessageResult (self: WsState, response: JsonRpcRespo
|
||||
const result = self.coder.decodeResponse(response);
|
||||
|
||||
if (subscription) {
|
||||
// flowlint-next-line unclear-type:off
|
||||
self.subscriptions[((result: any): number)] = {
|
||||
self.subscriptions[result as number] = {
|
||||
callback: subscription
|
||||
};
|
||||
}
|
||||
|
||||
handler.callback(null, result);
|
||||
} catch (error) {
|
||||
handler.callback(error);
|
||||
handler.callback(error, undefined);
|
||||
}
|
||||
|
||||
delete self.handlers[response.id];
|
||||
};
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const onMessage = require('./onMessage');
|
||||
const createState = require('./state');
|
||||
import onMessage from './onMessage';
|
||||
import createState from './state';
|
||||
|
||||
describe('onMessageSubscribe', () => {
|
||||
let state;
|
||||
|
||||
+5
-6
@@ -1,12 +1,11 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { JsonRpcResponse } from '../types';
|
||||
import type { WsState } from './types';
|
||||
import { JsonRpcResponse } from '../types';
|
||||
import { WsState } from './types';
|
||||
|
||||
module.exports = function onMessageSubscribe (self: WsState, response: JsonRpcResponse): void {
|
||||
export default function onMessageSubscribe (self: WsState, response: JsonRpcResponse): void {
|
||||
self.l.debug(() => ['handling: response =', response, 'subscription =', response.params.subscription]);
|
||||
|
||||
const handler = self.subscriptions[response.params.subscription];
|
||||
@@ -21,6 +20,6 @@ module.exports = function onMessageSubscribe (self: WsState, response: JsonRpcRe
|
||||
|
||||
handler.callback(null, result);
|
||||
} catch (error) {
|
||||
handler.callback(error);
|
||||
handler.callback(error, undefined);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { mockWs, TEST_WS_URL } = require('../../test/mockWs');
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
const create = require('./index');
|
||||
import create from './index';
|
||||
|
||||
let ws;
|
||||
let mock;
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { WsState } from './types';
|
||||
import { WsState } from './types';
|
||||
|
||||
module.exports = function onOpen (self: WsState): () => boolean {
|
||||
import assert from '@polkadot/util/assert';
|
||||
import isNull from '@polkadot/util/is/null';
|
||||
|
||||
export default function onOpen (self: WsState): () => boolean {
|
||||
return (): boolean => {
|
||||
assert(!isNull(self.websocket), 'WebSocket cannot be null in onOpen');
|
||||
|
||||
self.l.debug(() => ['connected to', self.endpoint]);
|
||||
|
||||
self.isConnected = true;
|
||||
@@ -14,13 +18,12 @@ module.exports = function onOpen (self: WsState): () => boolean {
|
||||
|
||||
Object.keys(self.queued).forEach((id) => {
|
||||
try {
|
||||
// @ts-ignore checked above
|
||||
self.websocket.send(
|
||||
// flowlint-next-line unclear-type:off
|
||||
self.queued[((id: any): number)]
|
||||
self.queued[id]
|
||||
);
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
delete self.queued[((id: any): number)];
|
||||
delete self.queued[id];
|
||||
} catch (error) {
|
||||
self.l.error(error);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
if (typeof WebSocket === 'undefined') {
|
||||
// @ts-ignore
|
||||
global.WebSocket = require('websocket').w3cwebsocket;
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { mockWs, TEST_WS_URL } = require('../../test/mockWs');
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
import index from './index';
|
||||
|
||||
let ws;
|
||||
let mock;
|
||||
@@ -12,7 +14,7 @@ function createMock (requests) {
|
||||
}
|
||||
|
||||
function createWs (autoConnect) {
|
||||
ws = require('./index')(TEST_WS_URL, autoConnect);
|
||||
ws = index(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface$Callback } from '../types';
|
||||
import type { WsState } from './types';
|
||||
import { ProviderInterface$Callback } from '../types';
|
||||
import { WsState } from './types';
|
||||
|
||||
module.exports = async function send (self: WsState, method: string, params: Array<mixed>, subscription?: ProviderInterface$Callback): Promise<mixed> {
|
||||
import isNull from '@polkadot/util/is/null';
|
||||
|
||||
export default async function send (self: WsState, method: string, params: Array<any>, subscription?: ProviderInterface$Callback): Promise<any> {
|
||||
return new Promise((resolve, reject): void => {
|
||||
try {
|
||||
const json = self.coder.encodeJson(method, params);
|
||||
const id = self.coder.getId();
|
||||
const callback = (error: ?Error, result: mixed) => {
|
||||
const callback = (error: Error | null, result: any) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
@@ -26,7 +27,7 @@ module.exports = async function send (self: WsState, method: string, params: Arr
|
||||
subscription
|
||||
};
|
||||
|
||||
if (self.isConnected) {
|
||||
if (self.isConnected && !isNull(self.websocket)) {
|
||||
self.websocket.send(json);
|
||||
} else {
|
||||
self.queued[id] = json;
|
||||
@@ -35,4 +36,4 @@ module.exports = async function send (self: WsState, method: string, params: Arr
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const state = require('./state');
|
||||
import state from './state';
|
||||
|
||||
describe('state', () => {
|
||||
it('requires an ws:// prefixed endpoint', () => {
|
||||
|
||||
@@ -1,28 +1,30 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { WsState } from './types';
|
||||
import { WsState } from './types';
|
||||
|
||||
const EventEmitter = require('eventemitter3');
|
||||
const assert = require('@polkadot/util/assert');
|
||||
const l = require('@polkadot/util/logger')('api-ws');
|
||||
import E3 from 'eventemitter3';
|
||||
import assert from '@polkadot/util/assert';
|
||||
import logger from '@polkadot/util/logger';
|
||||
|
||||
const coder = require('../coder/json');
|
||||
import coder from '../coder/json';
|
||||
|
||||
module.exports = function state (endpoint: string, autoConnect: boolean): $Shape<WsState> {
|
||||
const l = logger('api-ws');
|
||||
|
||||
export default function state (endpoint: string, autoConnect: boolean): WsState {
|
||||
assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`);
|
||||
|
||||
return {
|
||||
autoConnect,
|
||||
coder: coder(),
|
||||
emitter: new EventEmitter(),
|
||||
emitter: new E3.EventEmitter(),
|
||||
endpoint,
|
||||
handlers: {},
|
||||
isConnected: false,
|
||||
l,
|
||||
queued: {},
|
||||
subscriptions: {}
|
||||
subscriptions: {},
|
||||
websocket: null
|
||||
};
|
||||
};
|
||||
@@ -1,16 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { ProviderInterface$Callback } from '../types';
|
||||
import type { WsState } from './types';
|
||||
|
||||
const send = require('./send');
|
||||
|
||||
module.exports = async function subscribe (self: WsState, method: string, params: Array<mixed>, subscription: ProviderInterface$Callback): Promise<number> {
|
||||
const id = await send(self, method, params, subscription);
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
return ((id: any): number);
|
||||
};
|
||||
@@ -2,7 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { mockWs, TEST_WS_URL } = require('../../test/mockWs');
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
import index from './index';
|
||||
|
||||
let ws;
|
||||
let mock;
|
||||
@@ -12,7 +14,7 @@ function createMock (requests) {
|
||||
}
|
||||
|
||||
function createWs (autoConnect) {
|
||||
ws = require('./index')(TEST_WS_URL, autoConnect);
|
||||
ws = index(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface$Callback } from '../types';
|
||||
import { WsState } from './types';
|
||||
|
||||
import send from './send';
|
||||
|
||||
export default async function subscribe (self: WsState, method: string, params: Array<any>, subscription: ProviderInterface$Callback): Promise<number> {
|
||||
const id = await send(self, method, params, subscription);
|
||||
|
||||
return id as number;
|
||||
}
|
||||
+15
-10
@@ -1,12 +1,11 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type EventEmitter from 'eventemitter3';
|
||||
import type { Logger } from '@polkadot/util/types';
|
||||
import type { RpcCoder } from '../coder/json/types';
|
||||
import type { ProviderInterface$Callback } from '../types';
|
||||
import E3 from 'eventemitter3';
|
||||
import { Logger } from '@polkadot/util/types';
|
||||
import { RpcCoder } from '../coder/json/types';
|
||||
import { ProviderInterface$Callback } from '../types';
|
||||
|
||||
export type WsState$Awaiting = {
|
||||
callback: ProviderInterface$Callback,
|
||||
@@ -21,11 +20,17 @@ export type WsState = {
|
||||
autoConnect: boolean,
|
||||
coder: RpcCoder,
|
||||
endpoint: string,
|
||||
emitter: EventEmitter,
|
||||
handlers: { [number]: WsState$Awaiting },
|
||||
emitter: E3.EventEmitter,
|
||||
handlers: {
|
||||
[index: number]: WsState$Awaiting
|
||||
},
|
||||
isConnected: boolean,
|
||||
l: Logger,
|
||||
queued: { [number]: string },
|
||||
subscriptions: { [number]: WsState$Subscription },
|
||||
websocket: WebSocket
|
||||
queued: {
|
||||
[index: string]: string
|
||||
},
|
||||
subscriptions: {
|
||||
[index: number]: WsState$Subscription
|
||||
},
|
||||
websocket: WebSocket | null
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
// @flow
|
||||
|
||||
import type { WsState } from './types';
|
||||
|
||||
const assert = require('@polkadot/util/assert');
|
||||
const isUndefined = require('@polkadot/util/is/undefined');
|
||||
|
||||
const send = require('./send');
|
||||
|
||||
module.exports = async function unsubscribe (self: WsState, method: string, id: number): Promise<boolean> {
|
||||
assert(!isUndefined(self.subscriptions[id]), `Unable to find active subscription=${id}`);
|
||||
|
||||
delete self.subscriptions[id];
|
||||
|
||||
const result = await send(self, method, [id]);
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
return ((result: any): boolean);
|
||||
};
|
||||
@@ -2,7 +2,9 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { mockWs, TEST_WS_URL } = require('../../test/mockWs');
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
import index from './index';
|
||||
|
||||
let ws;
|
||||
let mock;
|
||||
@@ -12,7 +14,7 @@ function createMock (requests) {
|
||||
}
|
||||
|
||||
function createWs (autoConnect) {
|
||||
ws = require('./index')(TEST_WS_URL, autoConnect);
|
||||
ws = index(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2018 @polkadot/api-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { WsState } from './types';
|
||||
|
||||
import assert from '@polkadot/util/assert';
|
||||
import isUndefined from '@polkadot/util/is/undefined';
|
||||
|
||||
import send from './send';
|
||||
|
||||
export default async function unsubscribe (self: WsState, method: string, id: number): Promise<boolean> {
|
||||
assert(!isUndefined(self.subscriptions[id]), `Unable to find active subscription=${id}`);
|
||||
|
||||
delete self.subscriptions[id];
|
||||
|
||||
const result = await send(self, method, [id]);
|
||||
|
||||
return result as boolean;
|
||||
}
|
||||
@@ -2,11 +2,13 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const createApi = require('../../api/src');
|
||||
const createProvider = require('../src/ws');
|
||||
import { ApiInterface } from '../../api/src/types';
|
||||
|
||||
import createApi from '../../api/src';
|
||||
import createProvider from '../src/ws';
|
||||
|
||||
describe.skip('e2e', () => {
|
||||
let api;
|
||||
let api: ApiInterface;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.setTimeout(30000);
|
||||
@@ -17,7 +19,7 @@ describe.skip('e2e', () => {
|
||||
let count = 0;
|
||||
|
||||
api.chain
|
||||
.newHead((error, data) => {
|
||||
.newHead((error: Error | null, data: any) => {
|
||||
console.log('newHead: result =', [error, data]);
|
||||
|
||||
expect(data).toBeDefined();
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
declare module 'mock-socket' {
|
||||
export class Server {
|
||||
constructor (url: string);
|
||||
|
||||
on (event: 'message', body: {}): void;
|
||||
send (message: string): void;
|
||||
stop (): void;
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,17 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const nock = require('nock');
|
||||
import nock from 'nock';
|
||||
|
||||
const TEST_HTTP_URL = 'http://localhost:9944';
|
||||
|
||||
function mockHttp (requests) {
|
||||
function mockHttp (requests: any[]) {
|
||||
nock.cleanAll();
|
||||
|
||||
return requests.reduce((scope, request, index) => {
|
||||
return requests.reduce((scope, request: any, index: number) => {
|
||||
return scope
|
||||
.post('/')
|
||||
.reply(request.code || 200, (uri, body) => {
|
||||
.reply(request.code || 200, (uri: string, body: { id: string }) => {
|
||||
scope.body = scope.body || {};
|
||||
scope.body[request.method] = body;
|
||||
|
||||
@@ -21,7 +21,7 @@ function mockHttp (requests) {
|
||||
}, nock(TEST_HTTP_URL));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
TEST_HTTP_URL,
|
||||
mockHttp
|
||||
};
|
||||
@@ -2,13 +2,13 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
const { Server } = require('mock-socket');
|
||||
import { Server } from 'mock-socket';
|
||||
|
||||
const TEST_WS_URL = 'ws://localhost:9955';
|
||||
|
||||
let server;
|
||||
let server: Server;
|
||||
|
||||
function createError ({ id, error: { code, message } }) {
|
||||
function createError ({ id, error: { code, message } }: { id: number, error: { code: number, message: string } }) {
|
||||
return {
|
||||
id,
|
||||
jsonrpc: '2.0',
|
||||
@@ -19,7 +19,7 @@ function createError ({ id, error: { code, message } }) {
|
||||
};
|
||||
}
|
||||
|
||||
function createReply ({ id, reply: { result } }) {
|
||||
function createReply ({ id, reply: { result } }: { id: number, reply: { result: any }}) {
|
||||
return {
|
||||
id,
|
||||
jsonrpc: '2.0',
|
||||
@@ -27,21 +27,24 @@ function createReply ({ id, reply: { result } }) {
|
||||
};
|
||||
}
|
||||
|
||||
function mockWs (requests) {
|
||||
function mockWs (requests: Array<{ method: string }>) {
|
||||
server = new Server(TEST_WS_URL);
|
||||
|
||||
let requestCount = 0;
|
||||
const scope = {
|
||||
const scope: { body: { [index: string]: {} }, requests: number, server: Server, done: any } = {
|
||||
body: {},
|
||||
requests: 0,
|
||||
server,
|
||||
done: () => server.stop()
|
||||
};
|
||||
|
||||
server.on('message', (body) => {
|
||||
server.on('message', (body: {}) => {
|
||||
const request = requests[requestCount];
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
const response = request.error
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
? createError(request)
|
||||
// @ts-ignore Yes, SHOULD be fixed, this is a mess
|
||||
: createReply(request);
|
||||
|
||||
scope.body[request.method] = body;
|
||||
@@ -53,7 +56,7 @@ function mockWs (requests) {
|
||||
return scope;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
TEST_WS_URL,
|
||||
mockWs
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/api-rx",
|
||||
"version": "0.13.8",
|
||||
"version": "0.14.0",
|
||||
"description": "An RxJs wrapper around the Polkadot JS API",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -35,8 +35,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.0.0-beta.47",
|
||||
"@polkadot/api": "^0.13.8",
|
||||
"@polkadot/api-provider": "^0.13.8",
|
||||
"@polkadot/api": "^0.14.0",
|
||||
"@polkadot/api-provider": "^0.14.0",
|
||||
"@types/rx": "^4.1.1",
|
||||
"rxjs": "^5.5.10"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// 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 { ProviderInterface } from '@polkadot/api-provider/types';
|
||||
|
||||
const { BehaviorSubject } = require('rxjs/BehaviorSubject');
|
||||
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
|
||||
|
||||
module.exports = function connected (provider: ProviderInterface): rxjs$BehaviorSubject<boolean> {
|
||||
export default function connected (provider: ProviderInterface): BehaviorSubject<boolean> {
|
||||
const subject = new BehaviorSubject(provider.isConnected());
|
||||
|
||||
provider.on('connected', () => subject.next(true));
|
||||
provider.on('disconnected', () => subject.next(false));
|
||||
|
||||
return subject;
|
||||
};
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// 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
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface } from '@polkadot/api-provider/types';
|
||||
import { RxApiInterface } from '../types';
|
||||
|
||||
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
|
||||
|
||||
import createConnected from './connected';
|
||||
|
||||
export default function exposed (provider: ProviderInterface): RxApiInterface {
|
||||
const connected = createConnected(provider);
|
||||
|
||||
// @ts-ignore as in types.d.ts, not sure what to do here
|
||||
return {
|
||||
isConnected: (): BehaviorSubject<boolean> =>
|
||||
connected
|
||||
};
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// 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 = {
|
||||
export default {
|
||||
WS_URL
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// 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 createApi = require('@polkadot/api');
|
||||
const interfaces = require('@polkadot/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) => {
|
||||
result[type] = createInterface(api, type);
|
||||
|
||||
return result;
|
||||
}, exposed);
|
||||
};
|
||||
@@ -9,7 +9,7 @@ jest.mock('@polkadot/api-provider/ws', () => () => ({
|
||||
}));
|
||||
jest.mock('./interface', () => (api, sectionName) => sectionName);
|
||||
|
||||
const createApi = require('./index');
|
||||
const createApi = require('./index').default;
|
||||
|
||||
describe('createApi', () => {
|
||||
it('creates an instance with all sections', () => {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface } from '@polkadot/api-provider/types';
|
||||
import { RxApiInterface } from './types';
|
||||
|
||||
import createApi from '@polkadot/api/index';
|
||||
import interfaces from '@polkadot/jsonrpc';
|
||||
import createWs from '@polkadot/api-provider/ws';
|
||||
|
||||
import createExposed from './api';
|
||||
import defaults from './defaults';
|
||||
import createInterface from './interface';
|
||||
|
||||
export default function rxApi (provider: ProviderInterface = createWs(defaults.WS_URL)): RxApiInterface {
|
||||
const api = createApi(provider);
|
||||
const exposed = createExposed(provider);
|
||||
|
||||
return [...interfaces.keys()].reduce((result, type) => {
|
||||
result[type] = createInterface(api, type);
|
||||
|
||||
return result;
|
||||
}, exposed);
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
jest.mock('./observable', () => (subName, name, section) => `${subName}_${name}_${Object.keys(section).join(':')}`);
|
||||
|
||||
const createInterface = require('./interface');
|
||||
const createInterface = require('./interface').default;
|
||||
|
||||
describe('createInterface', () => {
|
||||
let api;
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// 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 { Interface$Sections } from '@polkadot/jsonrpc/types';
|
||||
import type { RxApiInterface$Section } from './types';
|
||||
import { ApiInterface, ApiInterface$Section } from '@polkadot/api/types';
|
||||
import { Interface$Sections } from '@polkadot/jsonrpc/types';
|
||||
import { RxApiInterface$Section } from './types';
|
||||
|
||||
const observable = require('./observable');
|
||||
import observable from './observable';
|
||||
|
||||
module.exports = function createInterface (api: ApiInterface, sectionName: Interface$Sections): RxApiInterface$Section {
|
||||
export default function createInterface (api: ApiInterface, sectionName: Interface$Sections): RxApiInterface$Section {
|
||||
const section: ApiInterface$Section = api[sectionName];
|
||||
|
||||
return Object
|
||||
@@ -19,5 +18,5 @@ module.exports = function createInterface (api: ApiInterface, sectionName: Inter
|
||||
observables[name] = observable(`${sectionName}_${name}`, name, section);
|
||||
|
||||
return observables;
|
||||
}, ({}: $Shape<RxApiInterface$Section>));
|
||||
};
|
||||
}, ({} as RxApiInterface$Section));
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/api-rx authors & contributors
|
||||
// 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]: {
|
||||
// flowlint-next-line unclear-type:off
|
||||
[Cached$ParamJson]: rxjs$BehaviorSubject<any>
|
||||
}
|
||||
};
|
||||
|
||||
const subject = require('./subject');
|
||||
|
||||
const cacheMap: CachedMap = {};
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
module.exports = function cached (subName: string, name: string, section: ApiInterface$Section): (...params: Array<mixed>) => rxjs$BehaviorSubject<any> {
|
||||
if (!cacheMap[subName]) {
|
||||
cacheMap[subName] = {};
|
||||
}
|
||||
|
||||
// flowlint-next-line unclear-type:off
|
||||
return (...params: Array<mixed>): rxjs$BehaviorSubject<any> => {
|
||||
const paramStr = JSON.stringify(params);
|
||||
|
||||
if (!cacheMap[subName][paramStr]) {
|
||||
cacheMap[subName][paramStr] = subject(name, params, section);
|
||||
}
|
||||
|
||||
return cacheMap[subName][paramStr];
|
||||
};
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user