UNPKG

1.35 kBPlain TextView Raw
1// Copyright 2017-2018 @polkadot/api-provider authors & contributors
2// This software may be modified and distributed under the terms
3// of the ISC license. See the LICENSE file for details.
4
5import { JsonRpcResponse, JsonRpcResponseBase$Error } from '../../types';
6import { RpcCoderState } from './types';
7
8import assert from '@polkadot/util/assert';
9import isNumber from '@polkadot/util/is/number';
10import isUndefined from '@polkadot/util/is/undefined';
11
12function 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
22export 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}