All files / src/service/gq-console index.js

89.39% Statements 59/66
87.23% Branches 41/47
77.78% Functions 7/9
90.77% Lines 59/65

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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187    6x 6x 6x 6x   6x 6x                                     25x                               32x 32x 32x         32x             32x   32x 3x 3x 3x     3x 3x     3x     29x   29x 28x     29x 9x         3x       6x     26x   26x 25x     26x   26x 6x 6x       26x             16x   16x                         16x     16x 16x 12x   4x         16x   16x 4x   4x 2x 2x 1x       4x     12x                 13x 13x 13x   13x   13x 13x   10x     4x               4x      
// @flow
 
import AbortController from 'abort-controller';
import { URL } from 'url';
import { createHmac } from 'crypto';
import fetch, { Headers, Response, Request } from 'node-fetch';
 
import logger from '../../logger';
import { ServiceError } from '../error';
 
export type GQConsoleConf = {
  apiKey?: string,
  metrics?: any,
  secretKey?: string,
  url: string,
  timeout?: number,
  legacy?: boolean,
};
 
export type GQConsoleRequestOptions = {
  version?: string,
  auth?: boolean,
  params?: { [string]: mixed },
  data?: any,
};
 
function getSignature(secretKey: string, url: URL): string {
  return createHmac('sha1', secretKey)
    .update(`${url.pathname}${url.search}`)
    .digest('base64');
}
 
export function getRequest(
  conf: GQConsoleConf,
  method: string,
  command: string,
  {
    version = 'api/v1',
    auth = false,
    params = {},
    data,
  }: GQConsoleRequestOptions,
): 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 = version ? `/${version}/${command}/` : `/${command}/`;
 
  if (auth && conf.apiKey && conf.secretKey) {
    const { apiKey: username, secretKey: password } = conf;
    const encodedPassword = Buffer.from(password).toString('base64');
    const encoded = Buffer.from(`${username}:${encodedPassword}`).toString(
      'base64',
    );
    headers.append('Content-Type', 'application/json; charset=utf-8');
    headers.append('Authorization', `Basic ${encoded}`);
 
    // $FlowFixMe
    return new Request(url.href, init);
  }
 
  url.searchParams.append('format', 'json');
 
  if (conf.apiKey) {
    url.searchParams.append('apikey', conf.apiKey);
  }
 
  Object.entries(params).forEach(([key, value]) => {
    if (
      value === null ||
      typeof value === 'undefined' ||
      typeof value.toString !== 'function'
    ) {
      throw new TypeError(`Value for param "${key}" must be string compatible`);
    }
 
    // $FlowFixMe
    url.searchParams.append(key, value.toString());
  });
 
  url.searchParams.sort();
 
  if (conf.secretKey) {
    url.searchParams.append('signature', getSignature(conf.secretKey, url));
  }
 
  logger.silly(url.href);
 
  if (data) {
    init.body = JSON.stringify(data);
    headers.append('Content-Type', 'application/json; charset=utf-8');
  }
 
  // $FlowFixMe
  return new Request(url.href, init);
}
 
export async function handleResponse(
  response: Response,
  { metrics, method, command, start }: any = {},
): Promise<mixed> {
  logger.silly(`GQ-console response=${JSON.stringify(response)}`);
 
  Iif (metrics) {
    metrics.histogram
      .labels(
        response.status,
        method,
        command
          .split('/')
          .filter(segment => Number.isNaN(parseInt(segment, 10)))
          .join('/'),
      )
      .observe(Date.now() - start);
  }
 
  const contentType = response.headers.get('Content-Type');
 
  let result;
  Eif (contentType) {
    if (contentType.includes('application/json')) {
      result = await response.json();
    } else {
      result = await response.text();
    }
  }
 
  // $FlowFixMe
  logger.debug(result);
 
  if (!response.ok) {
    let message = response.statusText;
 
    if (typeof result === 'string') {
      message = result;
    } else if (result && !(result instanceof ArrayBuffer)) {
      message =
        result.message || result.error || result.error_text || result.detail;
    }
 
    throw new ServiceError(response.status, message, result);
  }
 
  return result;
}
 
export default function callGQConsole(
  conf: GQConsoleConf,
  method: string,
  command: string,
  options: GQConsoleRequestOptions = {},
): Promise<any> {
  logger.debug(`GQConsole method=${method}`);
  logger.debug(`GQConsole command=${command}`);
  logger.debug(`GQConsole options=${JSON.stringify(options)}`);
 
  const start = Date.now();
 
  const request = getRequest(conf, method, command, options);
  return fetch(request)
    .then(result =>
      handleResponse(result, { metrics: conf.metrics, method, command, start }),
    )
    .catch(e => {
      Iif (e.type === 'aborted') {
        throw new ServiceError(
          408,
          `Request timeout: Timed out after ${conf.timeout || ''} milliseconds`,
          e,
        );
      }
 
      throw e;
    });
}