All files / src parser.js

39.29% Statements 11/28
37.5% Branches 9/24
60% Functions 3/5
39.29% Lines 11/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97                          1x             2x       2x 1x           1x 1x                               41x                 2x         2x   2x 2x                                                              
 
/**
 * Module dependencies.
 */
 
import JSONBigInt from 'json-bigint';
import RpcError from './errors/rpc-error';
import _ from 'lodash';
 
/**
 * JSONBigInt parser.
 */
 
const { parse } = JSONBigInt({ storeAsString: true, strict: true }); // eslint-disable-line new-cap
 
/**
 * Get response result and errors.
 */
 
function get(body, { headers = false, response } = {}) {
  Iif (!body) {
    throw new RpcError(response.statusCode, response.statusMessage);
  }
 
  if (body.error !== null) {
    throw new RpcError(
      _.get(body, 'error.code', -32603),
      _.get(body, 'error.message', 'An error occurred while processing the RPC call to bitcoind')
    );
  }
 
  Eif (!_.has(body, 'result')) {
    throw new RpcError(-32700, 'Missing `result` on the RPC call result');
  }
 
  if (headers) {
    return [body.result, response.headers];
  }
 
  return body.result;
}
 
/**
 * Export Parser class.
 */
 
export default class Parser {
  constructor({ headers } = {}) {
    this.headers = headers;
  }
 
  /**
   * Parse rpc response.
   */
 
  rpc([response, body]) {
    // Body contains HTML (e.g. 401 Unauthorized).
    Iif (typeof body === 'string' && response.headers['content-type'] !== 'application/json' && response.statusCode !== 200) {
      throw new RpcError(response.statusCode);
    }
 
    // Parsing the body with custom parser to support BigNumbers.
    body = parse(body);
 
    Eif (!Array.isArray(body)) {
      return get(body, { headers: this.headers, response });
    }
 
    // Batch response parsing where each response may or may not be successful.
    const batch = body.map(response => {
      try {
        return get(response, { headers: false, response });
      } catch (e) {
        return e;
      }
    });
 
    if (this.headers) {
      return [batch, response.headers];
    }
 
    return batch;
  }
 
  rest([response, body]) {
    if (body.error) {
      throw new RpcError(body.error.code, body.error.message);
    }
 
    if (this.headers) {
      return [body, response.headers];
    }
 
    return body;
  }
}