Classify JSONRPC coder (#341)
This commit is contained in:
committed by
Amaury Martiny
parent
9590e1d08e
commit
d6b6713418
+10
-9
@@ -2,48 +2,49 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import createCoder from './index';
|
||||
import { JsonRpcResponse } from '../types';
|
||||
import Coder from './index';
|
||||
|
||||
describe('decodeResponse', () => {
|
||||
let coder;
|
||||
let coder: Coder;
|
||||
|
||||
beforeEach(() => {
|
||||
coder = createCoder();
|
||||
coder = new Coder();
|
||||
});
|
||||
|
||||
it('expects a non-empty input object', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse()
|
||||
() => coder.decodeResponse((undefined as any) as JsonRpcResponse)
|
||||
).toThrow(/Empty response/);
|
||||
});
|
||||
|
||||
it('expects a valid jsonrpc field', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({})
|
||||
() => coder.decodeResponse({} as JsonRpcResponse)
|
||||
).toThrow(/Invalid jsonrpc/);
|
||||
});
|
||||
|
||||
it('expects a valid id field', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ jsonrpc: '2.0' })
|
||||
() => coder.decodeResponse({ jsonrpc: '2.0' } as JsonRpcResponse)
|
||||
).toThrow(/Invalid id/);
|
||||
});
|
||||
|
||||
it('expects a valid result field', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0' })
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0' } as JsonRpcResponse)
|
||||
).toThrow(/No result/);
|
||||
});
|
||||
|
||||
it('throws any error found', () => {
|
||||
expect(
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0', error: { code: 123, message: 'test error' } })
|
||||
() => coder.decodeResponse({ id: 1, jsonrpc: '2.0', error: { code: 123, message: 'test error' } } as JsonRpcResponse)
|
||||
).toThrow(/\[123\]: test error/);
|
||||
});
|
||||
|
||||
it('returns the result', () => {
|
||||
expect(
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', result: 'some result' })
|
||||
coder.decodeResponse({ id: 1, jsonrpc: '2.0', result: 'some result' } as JsonRpcResponse)
|
||||
).toEqual('some result');
|
||||
});
|
||||
});
|
||||
+3
-3
@@ -2,13 +2,13 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import createCoder from './index';
|
||||
import Coder from './index';
|
||||
|
||||
describe('encodeJson', () => {
|
||||
let coder;
|
||||
let coder: Coder;
|
||||
|
||||
beforeEach(() => {
|
||||
coder = createCoder();
|
||||
coder = new Coder();
|
||||
});
|
||||
|
||||
it('encodes a valid JsonRPC JSON string', () => {
|
||||
+3
-3
@@ -2,13 +2,13 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import createCoder from './index';
|
||||
import Coder from './index';
|
||||
|
||||
describe('encodeObject', () => {
|
||||
let coder;
|
||||
let coder: Coder;
|
||||
|
||||
beforeEach(() => {
|
||||
coder = createCoder();
|
||||
coder = new Coder();
|
||||
});
|
||||
|
||||
it('starts with id === 0 (nothing sent)', () => {
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-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, JsonRpcResponseBase$Error } from '../types';
|
||||
|
||||
import { assert, isUndefined, isNumber } from '@polkadot/util';
|
||||
|
||||
export default class RpcCoder {
|
||||
private id: number = 0;
|
||||
|
||||
decodeResponse (response: JsonRpcResponse): any {
|
||||
assert(response, 'Empty response object received');
|
||||
assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object');
|
||||
|
||||
const isSubscription = !isUndefined(response.params) && !isUndefined(response.method);
|
||||
|
||||
assert(isNumber(response.id) || (isSubscription && isNumber(response.params.subscription)), 'Invalid id field in decoded object');
|
||||
|
||||
this.checkError(response.error);
|
||||
|
||||
assert(!isUndefined(response.result) || isSubscription, 'No result found in JsonRpc response');
|
||||
|
||||
if (isSubscription) {
|
||||
this.checkError(response.params.error);
|
||||
|
||||
return response.params.result;
|
||||
}
|
||||
|
||||
return response.result;
|
||||
}
|
||||
|
||||
encodeJson (method: string, params: any | Array<any>): string {
|
||||
return JSON.stringify(
|
||||
this.encodeObject(method, params)
|
||||
);
|
||||
}
|
||||
|
||||
encodeObject (method: string, params: any | Array<any>): JsonRpcRequest {
|
||||
return {
|
||||
id: ++this.id,
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params
|
||||
};
|
||||
}
|
||||
|
||||
getId (): number {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
private checkError (error?: JsonRpcResponseBase$Error): void {
|
||||
if (error) {
|
||||
const { code, message } = error;
|
||||
|
||||
throw new Error(`[${code}]: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-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, JsonRpcResponseBase$Error } from '../../types';
|
||||
import { RpcCoderState } from './types';
|
||||
|
||||
import { assert, isNumber, isUndefined } from '@polkadot/util';
|
||||
|
||||
function checkError (error?: JsonRpcResponseBase$Error) {
|
||||
if (!error) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { code, message } = error;
|
||||
|
||||
throw new Error(`[${code}]: ${message}`);
|
||||
}
|
||||
|
||||
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');
|
||||
|
||||
const isSubscription = !isUndefined(response.params) && !isUndefined(response.method);
|
||||
|
||||
assert(isNumber(response.id) || (isSubscription && isNumber(response.params.subscription)), 'Invalid id field in decoded object');
|
||||
|
||||
checkError(response.error);
|
||||
|
||||
assert(!isUndefined(response.result) || isSubscription, 'No result found in JsonRpc response');
|
||||
|
||||
if (isSubscription) {
|
||||
checkError(response.params.error);
|
||||
|
||||
return response.params.result;
|
||||
}
|
||||
|
||||
return response.result;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-provider authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { RpcCoderState } from './types';
|
||||
|
||||
import encodeObject from './encodeObject';
|
||||
|
||||
export default function encodeJson (self: RpcCoderState, method: string, params: Array<any>): string {
|
||||
return JSON.stringify(
|
||||
encodeObject(self, method, params)
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-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 } from '../../types';
|
||||
import { RpcCoderState } from './types';
|
||||
|
||||
export default function encodeObject (self: RpcCoderState, method: string, params: Array<any>): JsonRpcRequest {
|
||||
return {
|
||||
id: ++self.id,
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params
|
||||
};
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-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
|
||||
};
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
// Copyright 2017-2018 @polkadot/rpc-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';
|
||||
|
||||
export type RpcCoder = {
|
||||
decodeResponse: (response: JsonRpcResponse) => any,
|
||||
encodeObject: (method: string, params: Array<any>) => JsonRpcRequest,
|
||||
encodeJson: (method: string, params: Array<any>) => string,
|
||||
getId: () => number
|
||||
};
|
||||
|
||||
export type RpcCoderState = {
|
||||
id: number
|
||||
};
|
||||
@@ -2,19 +2,19 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { Logger } from '@polkadot/util/types';
|
||||
import { RpcCoder } from '../coder/json/types';
|
||||
import { ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
|
||||
import './polyfill';
|
||||
|
||||
import { assert, logger } from '@polkadot/util';
|
||||
|
||||
import coder from '../coder/json';
|
||||
import Coder from '../coder';
|
||||
import defaults from '../defaults';
|
||||
|
||||
const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
|
||||
|
||||
const l = logger('api-http');
|
||||
|
||||
/**
|
||||
* # @polkadot/rpc-provider/https
|
||||
*
|
||||
@@ -36,9 +36,8 @@ const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSocke
|
||||
* @see [[WsProvider]]
|
||||
*/
|
||||
export default class HttpProvider implements ProviderInterface {
|
||||
private coder: RpcCoder;
|
||||
private coder: Coder;
|
||||
private endpoint: string;
|
||||
private l: Logger;
|
||||
|
||||
/**
|
||||
* @param {string} endpoint The endpoint url starting with http://
|
||||
@@ -46,9 +45,8 @@ export default class HttpProvider implements ProviderInterface {
|
||||
constructor (endpoint: string = defaults.HTTP_URL) {
|
||||
assert(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`);
|
||||
|
||||
this.coder = coder();
|
||||
this.coder = new Coder();
|
||||
this.endpoint = endpoint;
|
||||
this.l = logger('api-http');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,7 +62,7 @@ export default class HttpProvider implements ProviderInterface {
|
||||
* @description HTTP Provider does not have 'on' emitters. WebSockets should be used instead.
|
||||
*/
|
||||
on (type: ProviderInterface$Emitted, sub: ProviderInterface$EmitCb): void {
|
||||
this.l.error(`HTTP Provider does not have 'on' emitters, use WebSockets instead`);
|
||||
l.error(`HTTP Provider does not have 'on' emitters, use WebSockets instead`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,7 +91,7 @@ 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> {
|
||||
this.l.error(ERROR_SUBSCRIBE);
|
||||
l.error(ERROR_SUBSCRIBE);
|
||||
|
||||
throw new Error(ERROR_SUBSCRIBE);
|
||||
}
|
||||
@@ -102,7 +100,7 @@ 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> {
|
||||
this.l.error(ERROR_SUBSCRIBE);
|
||||
l.error(ERROR_SUBSCRIBE);
|
||||
|
||||
throw new Error(ERROR_SUBSCRIBE);
|
||||
}
|
||||
|
||||
+3
-2
@@ -3,10 +3,11 @@
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { Logger } from '@polkadot/util/types';
|
||||
import { RpcCoder } from '../coder/json/types';
|
||||
|
||||
import Coder from '../coder';
|
||||
|
||||
export type HttpState = {
|
||||
coder: RpcCoder,
|
||||
coder: Coder,
|
||||
endpoint: string,
|
||||
l: Logger
|
||||
};
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the ISC license. See the LICENSE file for details.
|
||||
|
||||
import { Logger } from '@polkadot/util/types';
|
||||
import { RpcCoder } from '../coder/json/types';
|
||||
import { JsonRpcResponse, ProviderInterface, ProviderInterface$Callback, ProviderInterface$Emitted, ProviderInterface$EmitCb } from '../types';
|
||||
|
||||
import './polyfill';
|
||||
@@ -11,7 +9,7 @@ import './polyfill';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { assert, isNull, isUndefined, logger } from '@polkadot/util';
|
||||
|
||||
import coder from '../coder/json';
|
||||
import Coder from '../coder';
|
||||
import defaults from '../defaults';
|
||||
|
||||
type CallbackHandler = (error?: null | Error, value?: any) => void;
|
||||
@@ -37,6 +35,8 @@ interface WSProviderInterface extends ProviderInterface {
|
||||
connect (): void;
|
||||
}
|
||||
|
||||
const l = logger('api-ws');
|
||||
|
||||
/**
|
||||
* # @polkadot/rpc-provider/ws
|
||||
*
|
||||
@@ -60,13 +60,12 @@ interface WSProviderInterface extends ProviderInterface {
|
||||
export default class WsProvider implements WSProviderInterface {
|
||||
private _eventemitter: EventEmitter;
|
||||
private autoConnect: boolean;
|
||||
private coder: RpcCoder;
|
||||
private coder: Coder;
|
||||
private endpoint: string;
|
||||
private handlers: {
|
||||
[index: number]: WsState$Awaiting
|
||||
};
|
||||
private _isConnected: boolean;
|
||||
private l: Logger;
|
||||
private queued: {
|
||||
[index: string]: string
|
||||
};
|
||||
@@ -84,11 +83,10 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
this._eventemitter = new EventEmitter();
|
||||
this.autoConnect = autoConnect;
|
||||
this.coder = coder();
|
||||
this.coder = new Coder();
|
||||
this.endpoint = endpoint;
|
||||
this._isConnected = false;
|
||||
this.handlers = {};
|
||||
this.l = logger('api-ws');
|
||||
this.queued = {};
|
||||
this.subscriptions = {};
|
||||
this.websocket = null;
|
||||
@@ -112,7 +110,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
this.websocket.onmessage = this.onSocketMessage;
|
||||
this.websocket.onopen = this.onSocketOpen;
|
||||
} catch (error) {
|
||||
this.l.error(error);
|
||||
l.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +147,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
}
|
||||
};
|
||||
|
||||
this.l.debug(() => ['calling', method, params, json, !!subscription]);
|
||||
l.debug(() => ['calling', method, params, json, !!subscription]);
|
||||
|
||||
this.handlers[id] = {
|
||||
callback,
|
||||
@@ -218,7 +216,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
}
|
||||
|
||||
private onSocketClose = (): void => {
|
||||
this.l.debug(() => ['disconnected from', this.endpoint]);
|
||||
l.debug(() => ['disconnected from', this.endpoint]);
|
||||
|
||||
this._isConnected = false;
|
||||
this.emit('disconnected');
|
||||
@@ -231,11 +229,11 @@ export default class WsProvider implements WSProviderInterface {
|
||||
}
|
||||
|
||||
private onSocketError = (error: Event): void => {
|
||||
this.l.error(error);
|
||||
l.error(error);
|
||||
}
|
||||
|
||||
private onSocketMessage = (message: MessageEvent): void => {
|
||||
this.l.debug(() => ['received', message.data]);
|
||||
l.debug(() => ['received', message.data]);
|
||||
|
||||
const response: JsonRpcResponse = JSON.parse(message.data as string);
|
||||
|
||||
@@ -245,12 +243,12 @@ export default class WsProvider implements WSProviderInterface {
|
||||
}
|
||||
|
||||
private onSocketMessageResult = (response: JsonRpcResponse): void => {
|
||||
this.l.debug(() => ['handling: response =', response, 'id =', response.id]);
|
||||
l.debug(() => ['handling: response =', response, 'id =', response.id]);
|
||||
|
||||
const handler = this.handlers[response.id];
|
||||
|
||||
if (!handler) {
|
||||
this.l.error(`Unable to find handler for id=${response.id}`);
|
||||
l.error(`Unable to find handler for id=${response.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -277,12 +275,12 @@ export default class WsProvider implements WSProviderInterface {
|
||||
private onSocketMessageSubscribe = (response: JsonRpcResponse): void => {
|
||||
const subscription = `${response.method}::${response.params.subscription}`;
|
||||
|
||||
this.l.debug(() => ['handling: response =', response, 'subscription =', subscription]);
|
||||
l.debug(() => ['handling: response =', response, 'subscription =', subscription]);
|
||||
|
||||
const handler = this.subscriptions[subscription];
|
||||
|
||||
if (!handler) {
|
||||
this.l.error(`Unable to find handler for subscription=${subscription}`);
|
||||
l.error(`Unable to find handler for subscription=${subscription}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -298,7 +296,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
private onSocketOpen = (): boolean => {
|
||||
assert(!isNull(this.websocket), 'WebSocket cannot be null in onOpen');
|
||||
|
||||
this.l.debug(() => ['connected to', this.endpoint]);
|
||||
l.debug(() => ['connected to', this.endpoint]);
|
||||
|
||||
this._isConnected = true;
|
||||
this.emit('connected');
|
||||
@@ -312,7 +310,7 @@ export default class WsProvider implements WSProviderInterface {
|
||||
|
||||
delete this.queued[id];
|
||||
} catch (error) {
|
||||
this.l.error(error);
|
||||
l.error(error);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user