All files / src/lib transport.js

100% Statements 10/10
100% Branches 8/8
100% Functions 3/3
100% Lines 10/10
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        2x 1x     1x               5x               5x 5x 3x 3x 3x     2x          
import request from 'request';
import SheetrockError from './error';
 
function getErrorMessage(error, resp) {
  if (resp && resp.statusCode) {
    return resp.statusCode;
  }
 
  return error.code;
}
 
// There is an issue with new Sheets causing the string ")]}'" to be
// prepended to the JSON output when the X-DataSource-Auth is added.
// Until this is fixed, load as text and manually strip with regex. :(
// https://github.com/google/google-visualization-issues/issues/1928
function get(response, callback) {
  const transportOptions = {
    headers: {
      'X-DataSource-Auth': 'true',
    },
    timeout: 5000,
    url: response.request.url,
  };
 
  request(transportOptions, (error, resp, body) => {
    if (!error && resp.statusCode === 200) {
      const data = JSON.parse(body.replace(/^\)\]\}'\n/, ''));
      response.loadData(data, callback);
      return;
    }
 
    callback(new SheetrockError('Request failed.', getErrorMessage(error, resp)));
  });
}
 
export default get;