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,
};
|