All files / src/service/network index.js

80.39% Statements 41/51
65% Branches 13/20
57.14% Functions 4/7
82% Lines 41/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139    1x 1x 1x   1x 1x                               4x 4x 4x         4x             4x 4x   4x 4x 4x 4x   4x     4x             6x 6x   6x                                   6x 2x   2x 2x         2x 2x   2x     4x 2x 2x   2x             2x 2x   2x                 1x 1x   1x   1x   1x 1x   1x                            
// @flow
 
import AbortController from 'abort-controller';
import fetch, { Headers, Request, Response } from 'node-fetch';
import { URL } from 'url';
 
import logger from '../../logger';
import { ServiceError } from '../error';
 
export type NetworkConf = {
  apiKey: string,
  metrics?: any,
  secretKey: string,
  url: string,
  timeout?: number,
};
 
export function getRequest(
  conf: NetworkConf,
  method: string,
  command: string,
  data?: any,
): Request {
  const url = new URL(conf.url);
  const headers = new Headers();
  const init: RequestOptions = {
    method,
    headers,
  };
 
  Iif (conf.timeout) {
    const controller = new AbortController();
    init.signal = controller.signal;
 
    setTimeout(() => controller.abort(), conf.timeout);
  }
 
  url.pathname = `/v1/${command}`;
  logger.silly(url.href);
 
  headers.append('Accept', 'application/json');
  headers.append('Content-Type', 'application/json');
  headers.append('Api-Key', conf.apiKey);
  headers.append('Secret-Key', conf.secretKey);
 
  init.body = JSON.stringify(data);
 
  // $FlowFixMe
  return new Request(url.href, init);
}
 
export async function handleResponse(
  response: Response,
  { metrics, method, command, start }: any = {},
): any {
  logger.silly(`CVN response=${JSON.stringify(response)}`);
  const contentType = response.headers.get('content-type');
 
  Iif (metrics) {
    metrics.histogram
      .labels(
        response.status,
        method,
        command
          .split('/')
          .filter(
            segment =>
              !segment.match(
                /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/,
              ),
          )
          .join('/'),
      )
      .observe(Date.now() - start);
  }
 
  if (!contentType || !contentType.includes('application/json')) {
    let message = 'Unable to process response: ';
 
    Eif (contentType) {
      message += `Expected content-type "application/json", proxy returned "${contentType}"`;
    } else {
      message += 'Missing response header "Content-Type"';
    }
 
    const text = await response.text();
    logger.debug(text);
 
    throw new ServiceError(400, message, text);
  }
 
  if (!response.ok) {
    const details = await response.json();
    logger.debug(details);
 
    throw new ServiceError(
      response.status,
      (details && details.message) || response.statusText,
      details,
    );
  }
 
  const result = await response.json();
  logger.debug(result);
 
  return result;
}
 
export default function callNetwork(
  conf: NetworkConf,
  method: string,
  command: string,
  data?: any,
): Promise<any> {
  logger.debug(`CVN method=${method}`);
  logger.debug(`CVN command=${command}`);
  // $FlowFixMe
  logger.debug(`CVN data=${JSON.stringify(data)}`);
 
  const start = Date.now();
 
  const request = getRequest(conf, method, command, data);
  return fetch(request)
    .then(result =>
      handleResponse(result, { metrics: conf.metrics, method, command, start }),
    )
    .catch(e => {
      if (e.type === 'aborted') {
        throw new ServiceError(
          408,
          `Request timeout: Timed out after ${conf.timeout || ''} milliseconds`,
          e,
        );
      }
 
      throw e;
    });
}