eslint rules (#1099)
* Off to the races - 3760 problems (1794 errors, 1966 warnings)
* Convert Array<T> -> T[] (not all correct, eg. extends)
* () => { -> (): void => {
* get is/as -> public get is/as
* public for getters, constructors & base Codec
* Some cleanups from previous overzealous search & replace
* Under 2k, 1874 problems (649 errors, 1225 warnings)
* ^^^ check that commit for details ;)
* Minor.
* rm config header
* Minor cleanups
* Default to tslint, eslint as option
* Trigger
* Update jsonrpc
* 1494 problems (433 errors, 1061 warnings)
* 1103 problems (135 errors, 968 warnings)
* 899 problems (9 errors, 890 warnings)
* 483 problems (9 errors, 474 warnings) (ignore any... for now)
* 366 problems (9 errors, 357 warnings)
* 336 problems (9 errors, 327 warnings)
* 148 problems (9 errors, 139 warnings)
* 31 problems (8 errors, 23 warnings)
* 0, 0
This commit is contained in:
@@ -5,46 +5,46 @@
|
||||
import { JsonRpcResponse } from '../types';
|
||||
import Coder from './';
|
||||
|
||||
describe('decodeResponse', () => {
|
||||
describe('decodeResponse', (): void => {
|
||||
let coder: Coder;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
coder = new Coder();
|
||||
});
|
||||
|
||||
it('expects a non-empty input object', () => {
|
||||
it('expects a non-empty input object', (): void => {
|
||||
expect(
|
||||
() => coder.decodeResponse((undefined as any) as JsonRpcResponse)
|
||||
(): any => coder.decodeResponse((undefined as any) as JsonRpcResponse)
|
||||
).toThrow(/Empty response/);
|
||||
});
|
||||
|
||||
it('expects a valid jsonrpc field', () => {
|
||||
it('expects a valid jsonrpc field', (): void => {
|
||||
expect(
|
||||
() => coder.decodeResponse({} as JsonRpcResponse)
|
||||
(): any => coder.decodeResponse({} as unknown as JsonRpcResponse)
|
||||
).toThrow(/Invalid jsonrpc/);
|
||||
});
|
||||
|
||||
it('expects a valid id field', () => {
|
||||
it('expects a valid id field', (): void => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ jsonrpc: '2.0' } as JsonRpcResponse)
|
||||
(): any => coder.decodeResponse({ jsonrpc: '2.0' } as unknown as JsonRpcResponse)
|
||||
).toThrow(/Invalid id/);
|
||||
});
|
||||
|
||||
it('expects a valid result field', () => {
|
||||
it('expects a valid result field', (): void => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0' } as JsonRpcResponse)
|
||||
(): any => coder.decodeResponse({ id: 1, jsonrpc: '2.0' } as unknown as JsonRpcResponse)
|
||||
).toThrow(/No result/);
|
||||
});
|
||||
|
||||
it('throws any error found', () => {
|
||||
it('throws any error found', (): void => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0', error: { code: 123, message: 'test error' } } as JsonRpcResponse)
|
||||
(): any => coder.decodeResponse({ id: 1, jsonrpc: '2.0', error: { code: 123, message: 'test error' } } as unknown as JsonRpcResponse)
|
||||
).toThrow(/123: test error/);
|
||||
});
|
||||
|
||||
it('returns the result', () => {
|
||||
it('returns the result', (): void => {
|
||||
expect(
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', result: 'some result' } as JsonRpcResponse)
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', result: 'some result' } as unknown as JsonRpcResponse)
|
||||
).toEqual('some result');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
|
||||
import Coder from './';
|
||||
|
||||
describe('encodeJson', () => {
|
||||
describe('encodeJson', (): void => {
|
||||
let coder: Coder;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
coder = new Coder();
|
||||
});
|
||||
|
||||
it('encodes a valid JsonRPC JSON string', () => {
|
||||
it('encodes a valid JsonRPC JSON string', (): void => {
|
||||
expect(
|
||||
coder.encodeJson('method', 'params')
|
||||
).toEqual('{"id":1,"jsonrpc":"2.0","method":"method","params":"params"}');
|
||||
|
||||
@@ -4,18 +4,18 @@
|
||||
|
||||
import Coder from './';
|
||||
|
||||
describe('encodeObject', () => {
|
||||
describe('encodeObject', (): void => {
|
||||
let coder: Coder;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
coder = new Coder();
|
||||
});
|
||||
|
||||
it('starts with id === 0 (nothing sent)', () => {
|
||||
it('starts with id === 0 (nothing sent)', (): void => {
|
||||
expect(coder.getId()).toEqual(0);
|
||||
});
|
||||
|
||||
it('encodes a valid JsonRPC object', () => {
|
||||
it('encodes a valid JsonRPC object', (): void => {
|
||||
expect(
|
||||
coder.encodeObject('method', 'params')
|
||||
).toEqual({
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { JsonRpcRequest, JsonRpcResponse, JsonRpcResponseBase$Error } from '../types';
|
||||
import { JsonRpcRequest, JsonRpcResponse, JsonRpcResponseBaseError } from '../types';
|
||||
|
||||
import { assert, isUndefined, isNumber } from '@polkadot/util';
|
||||
|
||||
export default class RpcCoder {
|
||||
private id: number = 0;
|
||||
|
||||
decodeResponse (response: JsonRpcResponse): any {
|
||||
public decodeResponse (response: JsonRpcResponse): any {
|
||||
assert(response, 'Empty response object received');
|
||||
assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object');
|
||||
|
||||
@@ -30,13 +30,13 @@ export default class RpcCoder {
|
||||
return response.result;
|
||||
}
|
||||
|
||||
encodeJson (method: string, params: any | Array<any>): string {
|
||||
public encodeJson (method: string, params: any | any[]): string {
|
||||
return JSON.stringify(
|
||||
this.encodeObject(method, params)
|
||||
);
|
||||
}
|
||||
|
||||
encodeObject (method: string, params: any | Array<any>): JsonRpcRequest {
|
||||
public encodeObject (method: string, params: any | any[]): JsonRpcRequest {
|
||||
return {
|
||||
id: ++this.id,
|
||||
jsonrpc: '2.0',
|
||||
@@ -45,16 +45,16 @@ export default class RpcCoder {
|
||||
};
|
||||
}
|
||||
|
||||
getId (): number {
|
||||
public getId (): number {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
private checkError (error?: JsonRpcResponseBase$Error): void {
|
||||
private checkError (error?: JsonRpcResponseBaseError): void {
|
||||
if (error) {
|
||||
const { code, data, message } = error;
|
||||
const _data = isUndefined(data)
|
||||
? ''
|
||||
: ' (' + `${data}`.substr(0, 10) + ')' ;
|
||||
: ' (' + `${data}`.substr(0, 10) + ')';
|
||||
|
||||
console.error(`${code}: ${message}${_data}`);
|
||||
|
||||
|
||||
@@ -5,37 +5,39 @@
|
||||
import { TEST_HTTP_URL } from '../../test/mockHttp';
|
||||
import Http from './';
|
||||
|
||||
describe('Http', () => {
|
||||
describe('Http', (): void => {
|
||||
let http: Http;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
http = new Http(TEST_HTTP_URL);
|
||||
});
|
||||
|
||||
it('requires an http:// prefixed endpoint', () => {
|
||||
it('requires an http:// prefixed endpoint', (): void => {
|
||||
expect(
|
||||
() => new Http('ws://')
|
||||
(): Http => new Http('ws://')
|
||||
).toThrow(/with 'http/);
|
||||
});
|
||||
|
||||
it('allows https:// endpoints', () => {
|
||||
it('allows https:// endpoints', (): void => {
|
||||
expect(
|
||||
() => new Http('https://')
|
||||
(): Http => new Http('https://')
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('always returns isConnected true', () => {
|
||||
it('always returns isConnected true', (): void => {
|
||||
expect(http.isConnected()).toEqual(true);
|
||||
});
|
||||
|
||||
it('does not (yet) support subscribe', () => {
|
||||
return http.subscribe('', '', [], (cb) => { expect(cb).toEqual(expect.anything()); }).catch((error) => {
|
||||
it('does not (yet) support subscribe', (): Promise<number | void> => {
|
||||
return http.subscribe('', '', [], (cb): void => {
|
||||
expect(cb).toEqual(expect.anything());
|
||||
}).catch((error): void => {
|
||||
expect(error.message).toMatch(/does not have subscriptions/);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not (yet) support unsubscribe', () => {
|
||||
return http.unsubscribe('', '', 0).catch((error) => {
|
||||
it('does not (yet) support unsubscribe', (): Promise<boolean | void> => {
|
||||
return http.unsubscribe('', '', 0).catch((error): void => {
|
||||
expect(error.message).toMatch(/does not have subscriptions/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types';
|
||||
|
||||
import './polyfill';
|
||||
|
||||
@@ -37,12 +37,13 @@ const l = logger('api-http');
|
||||
*/
|
||||
export default class HttpProvider implements ProviderInterface {
|
||||
private coder: Coder;
|
||||
|
||||
private endpoint: string;
|
||||
|
||||
/**
|
||||
* @param {string} endpoint The endpoint url starting with http://
|
||||
*/
|
||||
constructor (endpoint: string = defaults.HTTP_URL) {
|
||||
public constructor (endpoint: string = defaults.HTTP_URL) {
|
||||
assert(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`);
|
||||
|
||||
this.coder = new Coder();
|
||||
@@ -52,21 +53,21 @@ export default class HttpProvider implements ProviderInterface {
|
||||
/**
|
||||
* @summary `true` when this provider supports subscriptions
|
||||
*/
|
||||
get hasSubscriptions (): boolean {
|
||||
public get hasSubscriptions (): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a clone of the object
|
||||
*/
|
||||
clone (): HttpProvider {
|
||||
public clone (): HttpProvider {
|
||||
throw new Error('Unimplemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Manually disconnect from the connection
|
||||
*/
|
||||
disconnect (): void {
|
||||
public disconnect (): void {
|
||||
// noop
|
||||
}
|
||||
|
||||
@@ -74,7 +75,7 @@ export default class HttpProvider implements ProviderInterface {
|
||||
* @summary Whether the node is connected or not.
|
||||
* @return {boolean} true if connected
|
||||
*/
|
||||
isConnected (): boolean {
|
||||
public isConnected (): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -82,19 +83,20 @@ export default class HttpProvider implements ProviderInterface {
|
||||
* @summary Events are not supported with the HttpProvider, see [[WsProvider]].
|
||||
* @description HTTP Provider does not have 'on' emitters. WebSockets should be used instead.
|
||||
*/
|
||||
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): void {
|
||||
l.error(`HTTP Provider does not have 'on' emitters, use WebSockets instead`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
|
||||
*/
|
||||
async send (method: string, params: Array<any>): Promise<any> {
|
||||
public async send (method: string, params: any[]): Promise<any> {
|
||||
const body = this.coder.encodeJson(method, params);
|
||||
const response = await fetch(this.endpoint, {
|
||||
body,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'Content-Length': `${body.length}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
@@ -111,7 +113,8 @@ export default class HttpProvider implements ProviderInterface {
|
||||
/**
|
||||
* @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
|
||||
*/
|
||||
async subscribe (types: string, method: string, params: Array<any>, cb: ProviderInterface$Callback): Promise<number> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public async subscribe (types: string, method: string, params: any[], cb: ProviderInterfaceCallback): Promise<number> {
|
||||
l.error(ERROR_SUBSCRIBE);
|
||||
|
||||
throw new Error(ERROR_SUBSCRIBE);
|
||||
@@ -120,7 +123,8 @@ export default class HttpProvider implements ProviderInterface {
|
||||
/**
|
||||
* @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
|
||||
*/
|
||||
async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
l.error(ERROR_SUBSCRIBE);
|
||||
|
||||
throw new Error(ERROR_SUBSCRIBE);
|
||||
|
||||
@@ -6,26 +6,26 @@ import { Global } from './../mock/types';
|
||||
|
||||
declare const global: Global;
|
||||
|
||||
describe('http/polyfill', () => {
|
||||
describe('http/polyfill', (): void => {
|
||||
let origFetch: GlobalFetch;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
origFetch = global.fetch;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach((): void => {
|
||||
global.fetch = origFetch;
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (without fetch)', () => {
|
||||
it('polyfills with no exceptions (without fetch)', (): void => {
|
||||
(global as any).fetch = undefined;
|
||||
require('./polyfill');
|
||||
|
||||
expect(global.fetch).toBeDefined();
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (with fetch)', () => {
|
||||
(global as any).fetch = () => true;
|
||||
it('polyfills with no exceptions (with fetch)', (): void => {
|
||||
(global as any).fetch = (): boolean => true;
|
||||
require('./polyfill');
|
||||
|
||||
expect(global.fetch).toBeDefined();
|
||||
|
||||
@@ -6,21 +6,21 @@ import Http from './';
|
||||
import { Mock } from './../mock/types';
|
||||
import { mockHttp, TEST_HTTP_URL } from '../../test/mockHttp';
|
||||
|
||||
describe('send', () => {
|
||||
describe('send', (): void => {
|
||||
let http: Http;
|
||||
let mock: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
http = new Http(TEST_HTTP_URL);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach((): void => {
|
||||
if (mock) {
|
||||
mock.done();
|
||||
}
|
||||
});
|
||||
|
||||
it('passes the body through correctly', () => {
|
||||
it('passes the body through correctly', (): Promise<void> => {
|
||||
mock = mockHttp([{
|
||||
method: 'test_body',
|
||||
reply: {
|
||||
@@ -30,7 +30,7 @@ describe('send', () => {
|
||||
|
||||
return http
|
||||
.send('test_body', ['param'])
|
||||
.then((result) => {
|
||||
.then((): void => {
|
||||
expect((mock.body as any)['test_body']).toEqual({
|
||||
id: 1,
|
||||
jsonrpc: '2.0',
|
||||
@@ -40,7 +40,7 @@ describe('send', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('throws error when !response.ok', () => {
|
||||
it('throws error when !response.ok', (): Promise<any> => {
|
||||
mock = mockHttp([{
|
||||
code: 500,
|
||||
method: 'test_error'
|
||||
@@ -48,7 +48,7 @@ describe('send', () => {
|
||||
|
||||
return http
|
||||
.send('test_error', [])
|
||||
.catch((error) => {
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/\[500\]: Internal Server/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,8 +6,8 @@ import { Logger } from '@polkadot/util/types';
|
||||
|
||||
import Coder from '../coder';
|
||||
|
||||
export type HttpState = {
|
||||
coder: Coder,
|
||||
endpoint: string,
|
||||
l: Logger
|
||||
};
|
||||
export interface HttpState {
|
||||
coder: Coder;
|
||||
endpoint: string;
|
||||
l: Logger;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
// Copyright 2017-2019 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { MockState$Subscriptions, MockState$Subscription$Callback, MockState$Db } from './types';
|
||||
import { ProviderInterface, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types';
|
||||
import { MockStateSubscriptions, MockStateSubscriptionCallback, MockStateDb } from './types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
@@ -18,13 +19,13 @@ import { randomAsU8a } from '@polkadot/util-crypto';
|
||||
|
||||
const INTERVAL = 1000;
|
||||
const SUBSCRIPTIONS: string[] = Array.prototype.concat.apply(
|
||||
[], Object.values(interfaces).map((area) =>
|
||||
[], Object.values(interfaces).map((area): string[] =>
|
||||
Object
|
||||
.values(area.methods)
|
||||
.filter((method) =>
|
||||
.filter((method): boolean =>
|
||||
method.isSubscription
|
||||
)
|
||||
.map(({ method, section }) =>
|
||||
.map(({ method, section }): string =>
|
||||
`${section}_${method}`
|
||||
)
|
||||
)
|
||||
@@ -38,60 +39,65 @@ const l = logger('api-mock');
|
||||
* @return {ProviderInterface} The mock provider
|
||||
*/
|
||||
export default class Mock implements ProviderInterface {
|
||||
private db: MockState$Db = {};
|
||||
private db: MockStateDb = {};
|
||||
|
||||
private emitter = new EventEmitter();
|
||||
|
||||
public isUpdating: boolean = true;
|
||||
private requests: { [index: string]: (...params: any[]) => string } = {
|
||||
'chain_getBlockHash': (blockNumber: number): string => '0x1234',
|
||||
'chain_getRuntimeVersion': (): string => new RuntimeVersion().toHex(),
|
||||
'state_getStorage': (storage: MockState$Db, params: Array<any>): string => {
|
||||
|
||||
private requests: Record<string, (...params: any[]) => string> = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
chain_getBlockHash: (blockNumber: number): string => '0x1234',
|
||||
chain_getRuntimeVersion: (): string => new RuntimeVersion().toHex(),
|
||||
state_getStorage: (storage: MockStateDb, params: any[]): string => {
|
||||
return u8aToHex(
|
||||
storage[(params[0] as string)]
|
||||
);
|
||||
},
|
||||
'system_chain': (): string => 'mockChain',
|
||||
'state_getMetadata': (): string => rpcMetadataV6,
|
||||
'system_name': (): string => 'mockClient',
|
||||
'system_version': (): string => '9.8.7'
|
||||
system_chain: (): string => 'mockChain',
|
||||
state_getMetadata: (): string => rpcMetadataV6,
|
||||
system_name: (): string => 'mockClient',
|
||||
system_version: (): string => '9.8.7'
|
||||
};
|
||||
public subscriptions: MockState$Subscriptions = SUBSCRIPTIONS.reduce((subs, name) => {
|
||||
|
||||
public subscriptions: MockStateSubscriptions = SUBSCRIPTIONS.reduce((subs, name): MockStateSubscriptions => {
|
||||
subs[name] = {
|
||||
callbacks: {},
|
||||
lastValue: null
|
||||
};
|
||||
|
||||
return subs;
|
||||
}, ({} as MockState$Subscriptions));
|
||||
private subscriptionId: number = 0;
|
||||
private subscriptionMap: {
|
||||
[index: number]: string
|
||||
} = {};
|
||||
}, ({} as unknown as MockStateSubscriptions));
|
||||
|
||||
constructor () {
|
||||
private subscriptionId: number = 0;
|
||||
|
||||
private subscriptionMap: Record<number, string> = {};
|
||||
|
||||
public constructor () {
|
||||
this.init();
|
||||
}
|
||||
|
||||
get hasSubscriptions (): boolean {
|
||||
public get hasSubscriptions (): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
clone (): Mock {
|
||||
public clone (): Mock {
|
||||
throw new Error('Unimplemented');
|
||||
}
|
||||
|
||||
disconnect (): void {
|
||||
public disconnect (): void {
|
||||
// noop
|
||||
}
|
||||
|
||||
isConnected (): boolean {
|
||||
public isConnected (): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): void {
|
||||
this.emitter.on(type, sub);
|
||||
}
|
||||
|
||||
async send (method: string, params: Array<any>): Promise<any> {
|
||||
public async send (method: string, params: any[]): Promise<any> {
|
||||
if (!this.requests[method]) {
|
||||
throw new Error(`provider.send: Invalid method '${method}'`);
|
||||
}
|
||||
@@ -99,11 +105,11 @@ export default class Mock implements ProviderInterface {
|
||||
return this.requests[method](this.db, params);
|
||||
}
|
||||
|
||||
async subscribe (type: string, method: string, ...params: Array<any>): Promise<number> {
|
||||
l.debug(() => ['subscribe', method, params]);
|
||||
public async subscribe (type: string, method: string, ...params: any[]): Promise<number> {
|
||||
l.debug((): any => ['subscribe', method, params]);
|
||||
|
||||
if (this.subscriptions[method]) {
|
||||
const callback: MockState$Subscription$Callback = params.pop();
|
||||
const callback: MockStateSubscriptionCallback = params.pop();
|
||||
const id = ++this.subscriptionId;
|
||||
|
||||
this.subscriptions[method].callbacks[id] = callback;
|
||||
@@ -119,10 +125,10 @@ export default class Mock implements ProviderInterface {
|
||||
throw new Error(`provider.subscribe: Invalid method '${method}'`);
|
||||
}
|
||||
|
||||
async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
const sub = this.subscriptionMap[id];
|
||||
|
||||
l.debug(() => ['unsubscribe', id, sub]);
|
||||
l.debug((): any => ['unsubscribe', id, sub]);
|
||||
|
||||
if (!sub) {
|
||||
throw new Error(`Unable to find subscription for ${id}`);
|
||||
@@ -134,14 +140,14 @@ export default class Mock implements ProviderInterface {
|
||||
return true;
|
||||
}
|
||||
|
||||
private init () {
|
||||
const emitEvents: Array<ProviderInterface$Emitted> = ['connected', 'disconnected'];
|
||||
private init (): void {
|
||||
const emitEvents: ProviderInterfaceEmitted[] = ['connected', 'disconnected'];
|
||||
let emitIndex = 0;
|
||||
let newHead = this.makeBlockHeader(new BN(-1));
|
||||
let counter = -1;
|
||||
|
||||
// Do something every 1 seconds
|
||||
setInterval(() => {
|
||||
setInterval((): void => {
|
||||
if (!this.isUpdating) {
|
||||
return;
|
||||
}
|
||||
@@ -150,7 +156,7 @@ export default class Mock implements ProviderInterface {
|
||||
newHead = this.makeBlockHeader(newHead.blockNumber.toBn());
|
||||
|
||||
// increment the balances and nonce for each account
|
||||
keyring.getPairs().forEach(({ publicKey }, index) => {
|
||||
keyring.getPairs().forEach(({ publicKey }, index): void => {
|
||||
this.setStateBn(storage.balances.freeBalance(publicKey), newHead.blockNumber.muln(3).iaddn(index));
|
||||
this.setStateBn(storage.system.accountNonce(publicKey), newHead.blockNumber.addn(index));
|
||||
});
|
||||
@@ -190,12 +196,12 @@ export default class Mock implements ProviderInterface {
|
||||
this.db[u8aToHex(key)] = bnToU8a(value, 64, true);
|
||||
}
|
||||
|
||||
private updateSubs (method: string, value: Codec) {
|
||||
private updateSubs (method: string, value: Codec): void {
|
||||
this.subscriptions[method].lastValue = value;
|
||||
|
||||
Object
|
||||
.values(this.subscriptions[method].callbacks)
|
||||
.forEach((cb) => {
|
||||
.forEach((cb): void => {
|
||||
try {
|
||||
cb(null, value.toJSON());
|
||||
} catch (error) {
|
||||
|
||||
@@ -2,24 +2,24 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { ProviderInterface$Emitted } from '../types';
|
||||
import { ProviderInterfaceEmitted } from '../types';
|
||||
|
||||
import Mock from './';
|
||||
|
||||
describe('on', () => {
|
||||
describe('on', (): void => {
|
||||
let mock: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
mock = new Mock();
|
||||
});
|
||||
|
||||
it('it emits both connected and disconnected events', (done) => {
|
||||
const events: { [index: string]: boolean } = { connected: false, disconnected: false };
|
||||
const handler = (type: ProviderInterface$Emitted) => {
|
||||
mock.on(type, () => {
|
||||
it('it emits both connected and disconnected events', (done): void => {
|
||||
const events: Record<string, boolean> = { connected: false, disconnected: false };
|
||||
const handler = (type: ProviderInterfaceEmitted): void => {
|
||||
mock.on(type, (): void => {
|
||||
events[type] = true;
|
||||
|
||||
if (Object.values(events).filter((value) => value).length === 2) {
|
||||
if (Object.values(events).filter((value): boolean => value).length === 2) {
|
||||
done();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -4,25 +4,25 @@
|
||||
|
||||
import Mock from './';
|
||||
|
||||
describe('send', () => {
|
||||
describe('send', (): void => {
|
||||
let mock: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
mock = new Mock();
|
||||
});
|
||||
|
||||
it('fails on non-supported methods', () => {
|
||||
it('fails on non-supported methods', (): Promise<any> => {
|
||||
return mock
|
||||
.send('something_invalid', [])
|
||||
.catch((error) => {
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/Invalid method/);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns values for mocked requests', () => {
|
||||
it('returns values for mocked requests', (): Promise<void> => {
|
||||
return mock
|
||||
.send('system_name', [])
|
||||
.then((result) => {
|
||||
.then((result): void => {
|
||||
expect(result).toBe('mockClient');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,51 +4,51 @@
|
||||
|
||||
import Mock from './';
|
||||
|
||||
describe('subscribe', () => {
|
||||
describe('subscribe', (): void => {
|
||||
let mock: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
mock = new Mock();
|
||||
});
|
||||
|
||||
it('fails on unknown methods', () => {
|
||||
it('fails on unknown methods', (): Promise<number | void> => {
|
||||
return mock
|
||||
.subscribe('test', 'test_notFound')
|
||||
.catch((error) => {
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/Invalid method 'test_notFound'/);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a subscription id', () => {
|
||||
it('returns a subscription id', (): Promise<void> => {
|
||||
return mock
|
||||
.subscribe('chain_newHead', 'chain_subscribeNewHead', () => void 0)
|
||||
.then((id) => {
|
||||
.subscribe('chain_newHead', 'chain_subscribeNewHead', (): void => void 0)
|
||||
.then((id): void => {
|
||||
expect(id).toEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('calls back with the last known value', (done) => {
|
||||
it('calls back with the last known value', (done): Promise<number> => {
|
||||
mock.isUpdating = false;
|
||||
mock.subscriptions['chain_subscribeNewHead'].lastValue = 'testValue';
|
||||
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, value: string) => {
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, value: string): void => {
|
||||
expect(value).toEqual('testValue');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls back with new headers', (done) => {
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any) => {
|
||||
it('calls back with new headers', (done): Promise<number> => {
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => {
|
||||
if (header.number === 4) {
|
||||
done();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('handles errors withing callbacks gracefully', (done) => {
|
||||
let hasThrown: boolean = false;
|
||||
it('handles errors withing callbacks gracefully', (done): Promise<number> => {
|
||||
let hasThrown = false;
|
||||
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any) => {
|
||||
return mock.subscribe('chain_newHead', 'chain_subscribeNewHead', (_: any, header: any): void => {
|
||||
if (!hasThrown) {
|
||||
hasThrown = true;
|
||||
|
||||
|
||||
@@ -10,28 +10,20 @@ export interface Global extends NodeJS.Global {
|
||||
fetch: GlobalFetch;
|
||||
}
|
||||
|
||||
export type Mock = {
|
||||
body: Object,
|
||||
requests: Number,
|
||||
server: Server
|
||||
done: () => {}
|
||||
};
|
||||
export interface Mock {
|
||||
body: Record<string, any>;
|
||||
requests: number;
|
||||
server: Server;
|
||||
done: () => {};
|
||||
}
|
||||
|
||||
export type MockState$Subscription$Callback = (error: Error | null, value: any) => void;
|
||||
export type MockStateSubscriptionCallback = (error: Error | null, value: any) => void;
|
||||
|
||||
export type MockState$Subscriptions = {
|
||||
[index: string]: {
|
||||
callbacks: {
|
||||
[index: number]: MockState$Subscription$Callback
|
||||
},
|
||||
lastValue: any
|
||||
}
|
||||
};
|
||||
export type MockStateSubscriptions = Record<string, {
|
||||
callbacks: Record<number, MockStateSubscriptionCallback>;
|
||||
lastValue: any;
|
||||
}>;
|
||||
|
||||
export type MockState$Db = {
|
||||
[index: string]: Uint8Array
|
||||
};
|
||||
export type MockStateDb = Record<string, Uint8Array>;
|
||||
|
||||
export type MockState$Requests = {
|
||||
[index: string]: (db: MockState$Db, params: Array<any>) => string
|
||||
};
|
||||
export type MockStateRequests = Record<string, (db: MockStateDb, params: any[]) => string>;
|
||||
|
||||
@@ -4,37 +4,43 @@
|
||||
|
||||
import Mock from './';
|
||||
|
||||
describe('unsubscribe', () => {
|
||||
describe('unsubscribe', (): void => {
|
||||
let mock: Mock;
|
||||
let id: number;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): Promise<void> => {
|
||||
mock = new Mock();
|
||||
|
||||
return mock
|
||||
.subscribe('chain_newHead', 'chain_subscribeNewHead', () => void 0)
|
||||
.then((_id) => {
|
||||
.subscribe('chain_newHead', 'chain_subscribeNewHead', (): void => void 0)
|
||||
.then((_id): void => {
|
||||
id = _id;
|
||||
});
|
||||
});
|
||||
|
||||
it('fails on unknown ids', () => {
|
||||
it('fails on unknown ids', (): Promise<boolean> => {
|
||||
return mock
|
||||
.unsubscribe('chain_newHead', 'chain_subscribeNewHead', 5)
|
||||
.catch((error) => {
|
||||
.catch((error): boolean => {
|
||||
expect(error.message).toMatch(/Unable to find/);
|
||||
|
||||
return false;
|
||||
});
|
||||
});
|
||||
|
||||
it('unsubscribes successfully', () => {
|
||||
it('unsubscribes successfully', (): Promise<boolean> => {
|
||||
return mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id);
|
||||
});
|
||||
|
||||
it('fails on double unsubscribe', () => {
|
||||
it('fails on double unsubscribe', (): Promise<boolean> => {
|
||||
return mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id)
|
||||
.then(() => mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id))
|
||||
.catch((error) => {
|
||||
.then((): Promise<boolean> =>
|
||||
mock.unsubscribe('chain_newHead', 'chain_subscribeNewHead', id)
|
||||
)
|
||||
.catch((error): boolean => {
|
||||
expect(error.message).toMatch(/Unable to find/);
|
||||
|
||||
return false;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,53 +2,53 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
export type JsonRpcObject = {
|
||||
export interface JsonRpcObject {
|
||||
id: number;
|
||||
jsonrpc: '2.0';
|
||||
};
|
||||
}
|
||||
|
||||
export type JsonRpcRequest = JsonRpcObject & {
|
||||
export interface JsonRpcRequest extends JsonRpcObject {
|
||||
method: string;
|
||||
params: Array<any>;
|
||||
};
|
||||
params: any[];
|
||||
}
|
||||
|
||||
export type JsonRpcResponseBase$Error = {
|
||||
code: number,
|
||||
data?: number | string,
|
||||
message: string
|
||||
};
|
||||
export interface JsonRpcResponseBaseError {
|
||||
code: number;
|
||||
data?: number | string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
type JsonRpcResponse$Single = {
|
||||
error?: JsonRpcResponseBase$Error;
|
||||
interface JsonRpcResponseSingle {
|
||||
error?: JsonRpcResponseBaseError;
|
||||
result?: any;
|
||||
};
|
||||
}
|
||||
|
||||
type JsonRpcResponse$Subscription = {
|
||||
interface JsonRpcResponseSubscription {
|
||||
method?: string;
|
||||
params: {
|
||||
error?: JsonRpcResponseBase$Error;
|
||||
error?: JsonRpcResponseBaseError;
|
||||
result: any;
|
||||
subscription: number;
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export type JsonRpcResponseBase = JsonRpcResponse$Single & JsonRpcResponse$Subscription;
|
||||
export type JsonRpcResponseBase = JsonRpcResponseSingle & JsonRpcResponseSubscription;
|
||||
|
||||
export type JsonRpcResponse = JsonRpcObject & JsonRpcResponseBase;
|
||||
|
||||
export type ProviderInterface$Callback = (result: any) => void;
|
||||
export type ProviderInterfaceCallback = (result: any) => void;
|
||||
|
||||
export type ProviderInterface$Emitted = 'connected' | 'disconnected' | 'error';
|
||||
export type ProviderInterfaceEmitted = 'connected' | 'disconnected' | 'error';
|
||||
|
||||
export type ProviderInterface$EmitCb = (value?: any) => any;
|
||||
export type ProviderInterfaceEmitCb = (value?: any) => any;
|
||||
|
||||
export interface ProviderInterface {
|
||||
readonly hasSubscriptions: boolean;
|
||||
clone (): ProviderInterface;
|
||||
disconnect (): void;
|
||||
isConnected (): boolean;
|
||||
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void;
|
||||
send (method: string, params: Array<any>): Promise<any>;
|
||||
subscribe (type: string, method: string, params: Array<any>, cb: ProviderInterface$Callback): Promise<number>;
|
||||
on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): void;
|
||||
send (method: string, params: any[]): Promise<any>;
|
||||
subscribe (type: string, method: string, params: any[], cb: ProviderInterfaceCallback): Promise<number>;
|
||||
unsubscribe (type: string, method: string, id: number): Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/* eslint-disable @typescript-eslint/camelcase */
|
||||
// Copyright 2017-2019 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { JsonRpcResponse, ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
import { JsonRpcResponse, ProviderInterface, ProviderInterfaceCallback, ProviderInterfaceEmitted, ProviderInterfaceEmitCb } from '../types';
|
||||
|
||||
import './polyfill';
|
||||
|
||||
@@ -14,31 +15,31 @@ import defaults from '../defaults';
|
||||
|
||||
type CallbackHandler = (error?: null | Error, value?: any) => void;
|
||||
|
||||
type SubscriptionHandler = {
|
||||
callback: CallbackHandler,
|
||||
type: string
|
||||
};
|
||||
interface SubscriptionHandler {
|
||||
callback: CallbackHandler;
|
||||
type: string;
|
||||
}
|
||||
|
||||
type WsState$Awaiting = {
|
||||
callback: CallbackHandler,
|
||||
method: string,
|
||||
params: Array<any>,
|
||||
subscription?: SubscriptionHandler
|
||||
};
|
||||
interface WsStateAwaiting {
|
||||
callback: CallbackHandler;
|
||||
method: string;
|
||||
params: any[];
|
||||
subscription?: SubscriptionHandler;
|
||||
}
|
||||
|
||||
type WsState$Subscription = SubscriptionHandler & {
|
||||
method: string,
|
||||
params: Array<any>
|
||||
};
|
||||
interface WsStateSubscription extends SubscriptionHandler {
|
||||
method: string;
|
||||
params: any[];
|
||||
}
|
||||
|
||||
interface WSProviderInterface extends ProviderInterface {
|
||||
connect (): void;
|
||||
}
|
||||
|
||||
const ALIASSES: { [index: string]: string } = {
|
||||
'chain_finalisedHead': 'chain_finalizedHead',
|
||||
'chain_subscribeFinalisedHeads': 'chain_subscribeFinalizedHeads',
|
||||
'chain_unsubscribeFinalisedHeads': 'chain_unsubscribeFinalizedHeads'
|
||||
chain_finalisedHead: 'chain_finalizedHead',
|
||||
chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads',
|
||||
chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads'
|
||||
};
|
||||
|
||||
const l = logger('api-ws');
|
||||
@@ -65,29 +66,30 @@ const l = logger('api-ws');
|
||||
*/
|
||||
export default class WsProvider implements WSProviderInterface {
|
||||
private _eventemitter: EventEmitter;
|
||||
|
||||
private _isConnected: boolean = false;
|
||||
|
||||
private autoConnect: boolean;
|
||||
|
||||
private coder: Coder;
|
||||
|
||||
private endpoint: string;
|
||||
private handlers: {
|
||||
[index: string]: WsState$Awaiting
|
||||
};
|
||||
private queued: {
|
||||
[index: string]: string
|
||||
};
|
||||
private subscriptions: {
|
||||
[index: string]: WsState$Subscription
|
||||
};
|
||||
private waitingForId: {
|
||||
[index: string]: JsonRpcResponse
|
||||
};
|
||||
|
||||
private handlers: Record<string, WsStateAwaiting>;
|
||||
|
||||
private queued: Record<string, string>;
|
||||
|
||||
private subscriptions: Record<string, WsStateSubscription>;
|
||||
|
||||
private waitingForId: Record<string, JsonRpcResponse>;
|
||||
|
||||
private websocket: WebSocket | null;
|
||||
|
||||
/**
|
||||
* @param {string} endpoint The endpoint url. Usually `ws://ip:9944` or `wss://ip:9944`
|
||||
* @param {boolean} autoConnect Whether to connect automatically or not.
|
||||
*/
|
||||
constructor (endpoint: string = defaults.WS_URL, autoConnect: boolean = true) {
|
||||
public constructor (endpoint: string = defaults.WS_URL, autoConnect: boolean = true) {
|
||||
assert(/^(wss|ws):\/\//.test(endpoint), `Endpoint should start with 'ws://', received '${endpoint}'`);
|
||||
|
||||
this._eventemitter = new EventEmitter();
|
||||
@@ -108,14 +110,14 @@ export default class WsProvider implements WSProviderInterface {
|
||||
/**
|
||||
* @summary `true` when this provider supports subscriptions
|
||||
*/
|
||||
get hasSubscriptions (): boolean {
|
||||
public get hasSubscriptions (): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Returns a clone of the object
|
||||
*/
|
||||
clone (): WsProvider {
|
||||
public clone (): WsProvider {
|
||||
return new WsProvider(this.endpoint);
|
||||
}
|
||||
|
||||
@@ -124,7 +126,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* @description The [[WsProvider]] connects automatically by default, however if you decided otherwise, you may
|
||||
* connect manually using this method.
|
||||
*/
|
||||
connect (): void {
|
||||
public connect (): void {
|
||||
try {
|
||||
this.websocket = new WebSocket(this.endpoint);
|
||||
|
||||
@@ -140,7 +142,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
/**
|
||||
* @description Manually disconnect from the connection, clearing autoconnect logic
|
||||
*/
|
||||
disconnect (): void {
|
||||
public disconnect (): void {
|
||||
if (isNull(this.websocket)) {
|
||||
throw new Error('Cannot disconnect on a non-open websocket');
|
||||
}
|
||||
@@ -157,16 +159,16 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* @summary Whether the node is connected or not.
|
||||
* @return {boolean} true if connected
|
||||
*/
|
||||
isConnected (): boolean {
|
||||
public isConnected (): boolean {
|
||||
return this._isConnected;
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Listens on events after having subscribed using the [[subscribe]] function.
|
||||
* @param {ProviderInterface$Emitted} type Event
|
||||
* @param {ProviderInterface$EmitCb} sub Callback
|
||||
* @param {ProviderInterfaceEmitted} type Event
|
||||
* @param {ProviderInterfaceEmitCb} sub Callback
|
||||
*/
|
||||
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
public on (type: ProviderInterfaceEmitted, sub: ProviderInterfaceEmitCb): void {
|
||||
this._eventemitter.on(type, sub);
|
||||
}
|
||||
|
||||
@@ -176,18 +178,18 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* @param params Encoded paramaters as appliucable for the method
|
||||
* @param subscription Subscription details (internally used)
|
||||
*/
|
||||
send (method: string, params: Array<any>, subscription?: SubscriptionHandler): Promise<any> {
|
||||
public send (method: string, params: any[], subscription?: SubscriptionHandler): Promise<any> {
|
||||
return new Promise((resolve, reject): void => {
|
||||
try {
|
||||
const json = this.coder.encodeJson(method, params);
|
||||
const id = this.coder.getId();
|
||||
const callback = (error?: Error | null, result?: any) => {
|
||||
const callback = (error?: Error | null, result?: any): void => {
|
||||
error
|
||||
? reject(error)
|
||||
: resolve(result);
|
||||
};
|
||||
|
||||
l.debug(() => ['calling', method, params, json, !!subscription]);
|
||||
l.debug((): any[] => ['calling', method, params, json, !!subscription]);
|
||||
|
||||
this.handlers[id] = {
|
||||
callback,
|
||||
@@ -212,8 +214,8 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* @summary Allows subscribing to a specific event.
|
||||
* @param {string} type Subscription type
|
||||
* @param {string} method Subscription method
|
||||
* @param {Array<any>} params Parameters
|
||||
* @param {ProviderInterface$Callback} callback Callback
|
||||
* @param {any[]} params Parameters
|
||||
* @param {ProviderInterfaceCallback} callback Callback
|
||||
* @return {Promise<number>} Promise resolving to the dd of the subscription you can use with [[unsubscribe]].
|
||||
*
|
||||
* @example
|
||||
@@ -230,7 +232,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
async subscribe (type: string, method: string, params: Array<any>, callback: ProviderInterface$Callback): Promise<number> {
|
||||
public async subscribe (type: string, method: string, params: any[], callback: ProviderInterfaceCallback): Promise<number> {
|
||||
const id = await this.send(method, params, { callback, type });
|
||||
|
||||
return id as number;
|
||||
@@ -239,7 +241,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
/**
|
||||
* @summary Allows unsubscribing to subscriptions made with [[subscribe]].
|
||||
*/
|
||||
async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
public async unsubscribe (type: string, method: string, id: number): Promise<boolean> {
|
||||
const subscription = `${type}::${id}`;
|
||||
|
||||
// FIXME This now could happen with re-subscriptions. The issue is that with a re-sub
|
||||
@@ -247,7 +249,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
// a slight complication in solving - since we cannot rely on the send id, but rather
|
||||
// need to find the actual subscription id to map it
|
||||
if (isUndefined(this.subscriptions[subscription])) {
|
||||
l.debug(() => `Unable to find active subscription=${subscription}`);
|
||||
l.debug((): any => `Unable to find active subscription=${subscription}`);
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -259,7 +261,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
return result as boolean;
|
||||
}
|
||||
|
||||
private emit (type: ProviderInterface$Emitted, ...args: Array<any>): void {
|
||||
private emit (type: ProviderInterfaceEmitted, ...args: any[]): void {
|
||||
this._eventemitter.emit(type, ...args);
|
||||
}
|
||||
|
||||
@@ -272,19 +274,19 @@ export default class WsProvider implements WSProviderInterface {
|
||||
this.emit('disconnected');
|
||||
|
||||
if (this.autoConnect) {
|
||||
setTimeout(() => {
|
||||
setTimeout((): void => {
|
||||
this.connect();
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
private onSocketError = (error: Event): void => {
|
||||
l.debug(() => ['socket error', error]);
|
||||
l.debug((): any => ['socket error', error]);
|
||||
this.emit('error', error);
|
||||
}
|
||||
|
||||
private onSocketMessage = (message: MessageEvent): void => {
|
||||
l.debug(() => ['received', message.data]);
|
||||
l.debug((): any => ['received', message.data]);
|
||||
|
||||
const response: JsonRpcResponse = JSON.parse(message.data as string);
|
||||
|
||||
@@ -297,7 +299,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
const handler = this.handlers[response.id];
|
||||
|
||||
if (!handler) {
|
||||
l.debug(() => `Unable to find handler for id=${response.id}`);
|
||||
l.debug((): string => `Unable to find handler for id=${response.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -339,7 +341,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
// store the JSON, we could have out-of-order subid coming in
|
||||
this.waitingForId[subId] = response;
|
||||
|
||||
l.debug(() => `Unable to find handler for subscription=${subId}`);
|
||||
l.debug((): string => `Unable to find handler for subscription=${subId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -358,7 +360,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
private onSocketOpen = (): boolean => {
|
||||
assert(!isNull(this.websocket), 'WebSocket cannot be null in onOpen');
|
||||
|
||||
l.debug(() => ['connected to', this.endpoint]);
|
||||
l.debug((): any[] => ['connected to', this.endpoint]);
|
||||
|
||||
this._isConnected = true;
|
||||
this.emit('connected');
|
||||
@@ -374,7 +376,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
this.subscriptions = {};
|
||||
|
||||
Object.keys(subscriptions).forEach(async (id) => {
|
||||
Object.keys(subscriptions).forEach(async (id): Promise<void> => {
|
||||
const { callback, method, params, type } = subscriptions[id];
|
||||
|
||||
// only re-create subscriptions which are not in author (only area where
|
||||
@@ -393,7 +395,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
}
|
||||
|
||||
private sendQueue (): void {
|
||||
Object.keys(this.queued).forEach((id) => {
|
||||
Object.keys(this.queued).forEach((id): void => {
|
||||
try {
|
||||
// @ts-ignore we have done the websocket check in onSocketOpen, if an issue, will catch it
|
||||
this.websocket.send(
|
||||
|
||||
@@ -6,33 +6,33 @@ import WsProvider from './';
|
||||
import { Mock } from './../mock/types';
|
||||
import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
|
||||
describe('onConnect', () => {
|
||||
describe('onConnect', (): void => {
|
||||
let mock: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
mock = mockWs([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach((): void => {
|
||||
if (mock) {
|
||||
mock.done();
|
||||
}
|
||||
});
|
||||
|
||||
it('Does not connect when autoConnect is false', () => {
|
||||
it('Does not connect when autoConnect is false', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, false);
|
||||
// We need to access the private WsProvider property 'websocket' here which would otherwise trigger a tslint error.
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).toBeNull();
|
||||
});
|
||||
|
||||
it('Does connect when autoConnect is true', () => {
|
||||
it('Does connect when autoConnect is true', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, true);
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).not.toBeNull();
|
||||
});
|
||||
|
||||
it('Creates a new WebSocket instance by calling the connect() method', () => {
|
||||
it('Creates a new WebSocket instance by calling the connect() method', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL, false);
|
||||
// @ts-ignore
|
||||
expect(provider.websocket).toBeNull();
|
||||
@@ -45,7 +45,7 @@ describe('onConnect', () => {
|
||||
expect(provider.websocket instanceof WebSocket).toBe(true);
|
||||
});
|
||||
|
||||
it('Creates the on handlers', () => {
|
||||
it('Creates the on handlers', (): void => {
|
||||
const provider: WsProvider = new WsProvider(TEST_WS_URL);
|
||||
|
||||
// @ts-ignore
|
||||
|
||||
@@ -9,22 +9,23 @@ import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
let ws: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
function createWs (requests: Array<any>, autoConnect: boolean | undefined) {
|
||||
function createWs (requests: any[], autoConnect: boolean | undefined): WsProvider {
|
||||
mock = mockWs(requests);
|
||||
ws = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
describe('Ws', () => {
|
||||
afterEach(() => {
|
||||
describe('Ws', (): void => {
|
||||
afterEach((): void => {
|
||||
if (mock) {
|
||||
mock.done();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns the connected state', () => {
|
||||
it('returns the connected state', (): void => {
|
||||
expect(
|
||||
createWs([],true).isConnected()
|
||||
createWs([], true).isConnected()
|
||||
).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { default as WsProvider } from './Provider';
|
||||
import WsProvider from './Provider';
|
||||
|
||||
export default WsProvider;
|
||||
|
||||
@@ -4,18 +4,18 @@
|
||||
|
||||
import WsProvider from './';
|
||||
|
||||
describe('WsProvider', () => {
|
||||
describe('WsProvider', (): void => {
|
||||
let provider: WsProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
provider = new WsProvider('ws://127.0.0.1:1234', false);
|
||||
});
|
||||
|
||||
it('calls the handler when found', (done) => {
|
||||
it('calls the handler when found', (done): void => {
|
||||
// We need to access the private WsProvider property 'handlers' here which otherwise trigger a tslint error..
|
||||
// @ts-ignore
|
||||
provider.handlers[5] = {
|
||||
callback: (_: any, result: any) => {
|
||||
callback: (_: any, result: any): void => {
|
||||
expect(result).toEqual('test');
|
||||
done();
|
||||
},
|
||||
@@ -25,6 +25,8 @@ describe('WsProvider', () => {
|
||||
|
||||
// We need to access the private WsProvider property 'onSocketMessage' here which would otherwise trigger a tslint error.
|
||||
// @ts-ignore
|
||||
provider.onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","id":5,"result":"test"}' }));
|
||||
provider.onSocketMessage(
|
||||
new MessageEvent('test', { data: '{"jsonrpc":"2.0","id":5,"result":"test"}' })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,24 +4,24 @@
|
||||
|
||||
import WsProvider from './';
|
||||
|
||||
describe('onMessageSubscribe', () => {
|
||||
describe('onMessageSubscribe', (): void => {
|
||||
let provider: WsProvider;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
provider = new WsProvider('ws://127.0.0.1:1234', false);
|
||||
});
|
||||
|
||||
it('calls the subscriber with data', (done) => {
|
||||
it('calls the subscriber with data', (done): void => {
|
||||
// We need to access the private WsProvider property 'handlers' here which otherwise triggers a tslint error..
|
||||
// @ts-ignore
|
||||
provider.handlers[11] = {
|
||||
callback: (_: any, id: number) => {
|
||||
callback: (_: any, id: number): void => {
|
||||
expect(typeof id).toBe('number');
|
||||
},
|
||||
method: 'test',
|
||||
params: [],
|
||||
subscription: {
|
||||
callback: (_: any, result: any) => {
|
||||
callback: (_: any, result: any): void => {
|
||||
expect(result).toEqual('test');
|
||||
done();
|
||||
},
|
||||
@@ -36,17 +36,17 @@ describe('onMessageSubscribe', () => {
|
||||
provider.onSocketMessage(new MessageEvent('test', { data: '{"jsonrpc":"2.0","method":"test","params":{"subscription":22,"result":"test"}}' }));
|
||||
});
|
||||
|
||||
it('calls the subscriber with error', (done) => {
|
||||
it('calls the subscriber with error', (done): void => {
|
||||
// We need to access the private WsProvider property 'handlers' here which otherwise trigger a tslint error..
|
||||
// @ts-ignore
|
||||
provider.handlers[11] = {
|
||||
callback: (_: any, id: number) => {
|
||||
callback: (_: any, id: number): void => {
|
||||
expect(typeof id).toBe('number');
|
||||
},
|
||||
method: 'test',
|
||||
params: [],
|
||||
subscription: {
|
||||
callback: (error: any) => {
|
||||
callback: (error: any): void => {
|
||||
expect(error.message).toMatch(/test/);
|
||||
done();
|
||||
},
|
||||
|
||||
@@ -9,21 +9,21 @@ import { mockWs, TEST_WS_URL } from '../../test/mockWs';
|
||||
let ws: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
function createWs (requests: Array<any>, autoConnect: boolean | undefined) {
|
||||
function createWs (requests: any[], autoConnect: boolean | undefined): WsProvider {
|
||||
mock = mockWs(requests);
|
||||
ws = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
describe('onOpen', () => {
|
||||
afterEach(() => {
|
||||
describe('onOpen', (): void => {
|
||||
afterEach((): void => {
|
||||
if (mock) {
|
||||
mock.done();
|
||||
}
|
||||
});
|
||||
|
||||
it('sends messages when connected', () => {
|
||||
it('sends messages when connected', (): Promise<void> => {
|
||||
const ws = createWs([{
|
||||
id: 1,
|
||||
method: 'test_queue',
|
||||
@@ -35,7 +35,7 @@ describe('onOpen', () => {
|
||||
|
||||
ws.connect();
|
||||
|
||||
return sendPromise.then((result) => {
|
||||
return sendPromise.then((result): void => {
|
||||
expect(result).toEqual('ok');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,26 +8,26 @@ import { Global } from './../mock/types';
|
||||
|
||||
declare let global: Global;
|
||||
|
||||
describe('ws/polyfill', () => {
|
||||
describe('ws/polyfill', (): void => {
|
||||
let origWs: Constructor<WebSocket>;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
origWs = global.WebSocket;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach((): void => {
|
||||
global.WebSocket = origWs;
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (with WebSocket)', () => {
|
||||
it('polyfills with no exceptions (with WebSocket)', (): void => {
|
||||
(global as any).WebSocket = undefined;
|
||||
require('./polyfill');
|
||||
|
||||
expect(global.WebSocket).toBeDefined();
|
||||
});
|
||||
|
||||
it('polyfills with no exceptions (without WebSocket)', () => {
|
||||
(global as any).WebSocket = () => true;
|
||||
it('polyfills with no exceptions (without WebSocket)', (): void => {
|
||||
(global as any).WebSocket = (): boolean => true;
|
||||
require('./polyfill');
|
||||
|
||||
expect(global.WebSocket).toBeDefined();
|
||||
|
||||
@@ -12,24 +12,24 @@ declare const global: Global;
|
||||
let provider: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
function createMock (requests: Array<any>) {
|
||||
function createMock (requests: any[]): void {
|
||||
mock = mockWs(requests);
|
||||
}
|
||||
|
||||
function createWs (autoConnect: boolean = true) {
|
||||
function createWs (autoConnect: boolean = true): WsProvider {
|
||||
provider = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return provider;
|
||||
}
|
||||
|
||||
describe('send', () => {
|
||||
describe('send', (): void => {
|
||||
let globalWs: Constructor<WebSocket>;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
globalWs = global.WebSocket;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach((): void => {
|
||||
global.WebSocket = globalWs;
|
||||
|
||||
if (mock) {
|
||||
@@ -37,11 +37,11 @@ describe('send', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('handles internal errors', () => {
|
||||
it('handles internal errors', (): Promise<any> => {
|
||||
createMock([]);
|
||||
|
||||
(global as any).WebSocket = class {
|
||||
send () {
|
||||
public send (): void {
|
||||
throw new Error('send error');
|
||||
}
|
||||
};
|
||||
@@ -52,12 +52,12 @@ describe('send', () => {
|
||||
|
||||
return provider
|
||||
.send('test_encoding', ['param'])
|
||||
.catch((error) => {
|
||||
.catch((error): void => {
|
||||
expect(error.message).toEqual('send error');
|
||||
});
|
||||
});
|
||||
|
||||
it('passes the body through correctly', () => {
|
||||
it('passes the body through correctly', (): Promise<void> => {
|
||||
createMock([{
|
||||
id: 1,
|
||||
method: 'test_body',
|
||||
@@ -68,14 +68,14 @@ describe('send', () => {
|
||||
|
||||
return createWs(true)
|
||||
.send('test_body', ['param'])
|
||||
.then((result) => {
|
||||
.then((): void => {
|
||||
expect(
|
||||
(mock.body as any)['test_body']
|
||||
).toEqual('{"id":1,"jsonrpc":"2.0","method":"test_body","params":["param"]}');
|
||||
});
|
||||
});
|
||||
|
||||
it('throws error when !response.ok', () => {
|
||||
it('throws error when !response.ok', (): Promise<any> => {
|
||||
createMock([{
|
||||
id: 1,
|
||||
error: {
|
||||
@@ -86,12 +86,12 @@ describe('send', () => {
|
||||
|
||||
return createWs(true)
|
||||
.send('test_error', [])
|
||||
.catch((error) => {
|
||||
.catch((error): void => {
|
||||
expect(error.message).toMatch(/666: error/);
|
||||
});
|
||||
});
|
||||
|
||||
it('adds subscriptions', () => {
|
||||
it('adds subscriptions', (): Promise<void> => {
|
||||
createMock([{
|
||||
id: 1,
|
||||
method: 'test_sub',
|
||||
@@ -102,7 +102,7 @@ describe('send', () => {
|
||||
|
||||
return createWs(true)
|
||||
.send('test_sub', [])
|
||||
.then((id) => {
|
||||
.then((id): void => {
|
||||
expect(id).toEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,16 +4,16 @@
|
||||
|
||||
import WsProvider from './';
|
||||
|
||||
describe('state', () => {
|
||||
it('requires an ws:// prefixed endpoint', () => {
|
||||
describe('state', (): void => {
|
||||
it('requires an ws:// prefixed endpoint', (): void => {
|
||||
expect(
|
||||
() => new WsProvider('http://', false)
|
||||
(): WsProvider => new WsProvider('http://', false)
|
||||
).toThrow(/with 'ws/);
|
||||
});
|
||||
|
||||
it('allows wss:// endpoints', () => {
|
||||
it('allows wss:// endpoints', (): void => {
|
||||
expect(
|
||||
() => new WsProvider('wss://', false)
|
||||
(): WsProvider => new WsProvider('wss://', false)
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,24 +12,24 @@ declare var global: Global;
|
||||
let ws: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
function createMock (requests: Array<any>) {
|
||||
function createMock (requests: any[]): void {
|
||||
mock = mockWs(requests);
|
||||
}
|
||||
|
||||
function createWs (autoConnect: boolean = true) {
|
||||
function createWs (autoConnect: boolean = true): WsProvider {
|
||||
ws = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
describe('subscribe', () => {
|
||||
describe('subscribe', (): void => {
|
||||
let globalWs: Constructor<WebSocket>;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
globalWs = global.WebSocket;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach((): void => {
|
||||
global.WebSocket = globalWs;
|
||||
|
||||
if (mock) {
|
||||
@@ -37,7 +37,7 @@ describe('subscribe', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('adds subscriptions', () => {
|
||||
it('adds subscriptions', (): Promise<void> => {
|
||||
createMock([{
|
||||
id: 1,
|
||||
method: 'test_sub',
|
||||
@@ -47,8 +47,10 @@ describe('subscribe', () => {
|
||||
}]);
|
||||
|
||||
return createWs(true)
|
||||
.subscribe('type', 'test_sub', [], (cb) => { expect(cb).toEqual(expect.anything()); })
|
||||
.then((id) => {
|
||||
.subscribe('type', 'test_sub', [], (cb): void => {
|
||||
expect(cb).toEqual(expect.anything());
|
||||
})
|
||||
.then((id): void => {
|
||||
expect(id).toEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,24 +12,24 @@ declare var global: Global;
|
||||
let ws: WsProvider;
|
||||
let mock: Mock;
|
||||
|
||||
function createMock (requests: any) {
|
||||
function createMock (requests: any): void {
|
||||
mock = mockWs(requests);
|
||||
}
|
||||
|
||||
function createWs (autoConnect: boolean = true) {
|
||||
function createWs (autoConnect: boolean = true): WsProvider {
|
||||
ws = new WsProvider(TEST_WS_URL, autoConnect);
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
describe('subscribe', () => {
|
||||
describe('subscribe', (): void => {
|
||||
let globalWs: Constructor<WebSocket>;
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach((): void => {
|
||||
globalWs = global.WebSocket;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
afterEach((): void => {
|
||||
global.WebSocket = globalWs;
|
||||
|
||||
if (mock) {
|
||||
@@ -37,7 +37,7 @@ describe('subscribe', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('removes subscriptions', () => {
|
||||
it('removes subscriptions', (): Promise<boolean> => {
|
||||
createMock([
|
||||
{
|
||||
id: 1,
|
||||
@@ -58,13 +58,15 @@ describe('subscribe', () => {
|
||||
const ws = createWs(true);
|
||||
|
||||
return ws
|
||||
.subscribe('test', 'subscribe_test', [], (cb) => { expect(cb).toEqual(expect.anything()); })
|
||||
.then((id) => {
|
||||
.subscribe('test', 'subscribe_test', [], (cb): void => {
|
||||
expect(cb).toEqual(expect.anything());
|
||||
})
|
||||
.then((id): Promise<boolean> => {
|
||||
return ws.unsubscribe('test', 'subscribe_test', id);
|
||||
});
|
||||
});
|
||||
|
||||
it('fails when sub not found', () => {
|
||||
it('fails when sub not found', (): Promise<void> => {
|
||||
createMock([{
|
||||
id: 1,
|
||||
method: 'subscribe_test',
|
||||
@@ -76,11 +78,13 @@ describe('subscribe', () => {
|
||||
const ws = createWs(true);
|
||||
|
||||
return ws
|
||||
.subscribe('test', 'subscribe_test', [], (cb) => { expect(cb).toEqual(expect.anything()); })
|
||||
.then((id) => {
|
||||
.subscribe('test', 'subscribe_test', [], (cb): void => {
|
||||
expect(cb).toEqual(expect.anything());
|
||||
})
|
||||
.then((): Promise<boolean> => {
|
||||
return ws.unsubscribe('test', 'subscribe_test', 111);
|
||||
})
|
||||
.then((result) => {
|
||||
.then((result): void => {
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user