all files / src/ index.js

43.9% Statements 18/41
28.57% Branches 4/14
9.09% Functions 1/11
42.31% Lines 11/26
1 branch Ignored     
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                                                                                                                                        
import reqLib from 'request';
import fs from 'fs';
import url from 'url';
import util from 'util';
 
const get = filePath => new Promise((resolve, reject) => {
  fs.readFile(filePath, (err, buf) => {
    if (err) reject(err);
    else resolve(buf.toString());
  });
});
 
const log = (title, obj) => {
  console.log(`\n-------------------------\n${title}\n-------------------------`);
  console.log(util.inspect(obj, {
    depth: 4,
    colors: true,
  }));
};
 
const parseResponse = (res, isDownload) => ({
  status: res.statusCode,
  statusText: res.statusMessage,
  headers: res.headers,
  body: isDownload ? '' : res.body.toString(),
});
 
/**
 * config properties:
 * url - string - url to call
 * method - string - http method
 * query - object - query hash
 * headers - object - headers hash
 * body - string - body to send
 * importFile - string - file path for upload
 * exportFile - string - file path for download
 * upload - string - name of the form field for upload
 */
const request = (config, logg) => new Promise((resolve, reject) => {
  const options = {
    uri: config.url,
    method: config.method,
    headers: config.headers,
    body: config.body,
    qs: config.query,
  };
 
  if (config.importFile) {
    logg('Request Configuration',
      Object.assign({}, options, { formData: config.importFile }));
    options.formData = {};
    options.formData[config.formField] = fs.createReadStream(config.importFile);
  } else {
    logg('Request Configuration', options);
  }
 
  const req = reqLib(options, (err, res) => {
    if (err) reject(err);
    else {
      resolve(parseResponse(res, config.exportFile !== undefined));
    }
  });
  if (config.exportFile) req.pipe(fs.createWriteStream(config.exportFile));
});
 
const urlParse = urlString => url.parse(urlString, true);
 
const btoa = str => new Buffer(str, 'utf8').toString('base64');
 
export default {
  get,
  request,
  urlParse,
  log,
  btoa,
};