1 |
|
2 |
|
3 |
|
4 |
|
5 | import { JsonRpcResponse, JsonRpcResponseBase$Error } from '../../types';
|
6 | import { RpcCoderState } from './types';
|
7 |
|
8 | import assert from '@polkadot/util/assert';
|
9 | import isNumber from '@polkadot/util/is/number';
|
10 | import isUndefined from '@polkadot/util/is/undefined';
|
11 |
|
12 | function checkError (error?: JsonRpcResponseBase$Error) {
|
13 | if (!error) {
|
14 | return;
|
15 | }
|
16 |
|
17 | const { code, message } = error;
|
18 |
|
19 | throw new Error(`[${code}]: ${message}`);
|
20 | }
|
21 |
|
22 | export default function decodeResponse (self: RpcCoderState, response: JsonRpcResponse): any {
|
23 | assert(response, 'Empty response object received');
|
24 | assert(response.jsonrpc === '2.0', 'Invalid jsonrpc field in decoded object');
|
25 |
|
26 | const isSubscription = !isUndefined(response.params) && !isUndefined(response.method);
|
27 |
|
28 | assert(isNumber(response.id) || (isSubscription && isNumber(response.params.subscription)), 'Invalid id field in decoded object');
|
29 |
|
30 | checkError(response.error);
|
31 |
|
32 | assert(!isUndefined(response.result) || isSubscription, 'No result found in JsonRpc response');
|
33 |
|
34 | if (isSubscription) {
|
35 | checkError(response.params.error);
|
36 |
|
37 | return response.params.result;
|
38 | }
|
39 |
|
40 | return response.result;
|
41 | }
|