All files / src/service/cloud-sync index.js

81.63% Statements 40/49
70% Branches 14/20
62.5% Functions 5/8
83.33% Lines 40/48

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    2x 2x 2x   2x 2x                                 6x 6x 6x         6x             6x 1x     3x 1x   2x       6x 6x   6x 6x 6x 6x 6x   6x   6x     6x             6x   6x                           6x 6x         6x 2x   2x     4x                   2x 2x   2x   2x   2x   2x 2x   2x                            
// @flow
 
import AbortController from 'abort-controller';
import { URL } from 'url';
import fetch, { Headers, Request, Response } from 'node-fetch';
 
import logger from '../../logger';
import { ServiceError } from '../error';
 
export type CloudSyncConf = {
  metrics?: any,
  onbehalfToken: string,
  token: string,
  url: string,
  timeout?: number,
};
 
export function getRequest(
  conf: CloudSyncConf,
  method: string,
  command: string,
  data?: any,
  params?: 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);
  }
 
  if (params) {
    Object.entries(params)
      .sort()
      .forEach(([key, value]) => {
        if (typeof value !== 'string') {
          return;
        }
        url.searchParams.append(key, value);
      });
  }
 
  url.pathname = `/api/${command}`;
  logger.silly(url.href);
 
  headers.append('Accept', 'application/json');
  headers.append('Authorization', `Bearer ${conf.token}`);
  headers.append('Connection', 'keep-alive');
  headers.append('Content-Type', 'application/json');
  headers.append('x-netapp-on-behalf', `Bearer ${conf.onbehalfToken}`);
 
  logger.debug(`CloudSync href=${url.href}`);
 
  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(`CloudSync response=${JSON.stringify(response)}`);
 
  Iif (metrics) {
    metrics.histogram
      .labels(
        response.status,
        method,
        command
          .split('/')
          .filter(segment => !segment.match(/^[a-fA-F0-9]+$/g))
          .join('/'),
      )
      .observe(Date.now() - start);
  }
 
  let result;
  try {
    result = await response.json();
  } catch (e) {
    // Not json, for some reason
  }
 
  if (!response.ok) {
    const message = (result && result.message) || response.statusText;
 
    throw new ServiceError(response.status, message, result);
  }
 
  return result || {};
}
 
export default function callCloudSync(
  conf: CloudSyncConf,
  method: string,
  command: string,
  data?: any,
  params?: any,
): Promise<any> {
  logger.debug(`CloudSync method=${method}`);
  logger.debug(`CloudSync command=${command}`);
  // $FlowFixMe
  logger.debug(`CloudSync data=${JSON.stringify(data)}`);
  // $FlowFixMe
  logger.debug(`CloudSync params=${JSON.stringify(params)}`);
 
  const start = Date.now();
 
  const request = getRequest(conf, method, command, data, params);
  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;
    });
}