UNPKG

stratumn-cli

Version:
99 lines (81 loc) 2.38 kB
import util from 'util'; import { parse } from 'url'; import superagent from 'superagent'; import proxy from 'superagent-proxy'; import config from '../config'; import loadConfig from './loadConfig'; import saveConfig from './saveConfig'; import filterKeys from './filterKeys'; if (config.allowUnauthorizedTls) { process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; } // Monkey patch superagent with proxy functionality if needed if (config.proxy) { proxy(superagent); } function exec(method, path, payload, jwt, app) { return new Promise((resolve, reject) => { let url; if (app) { if (config.applicationUrl.indexOf('%s') > -1) { url = util.format(config.applicationUrl, app) + path; } else { url = config.applicationUrl + path; } } else { url = config.baseUrl + path; } if (config.debug) { console.log(`Requesting ${method} ${url}`); } let req = superagent[method](url); if (jwt) { req = req .set('Authorization', 'JWT ' + jwt) .set('X-Refresh-Jwt', 1); } if (payload) { req = req.send(payload); } // Proxy request if needed. if (config.proxy) { if (config.debug) { const obj = filterKeys(parse(config.proxy), 'protocol', 'hostname', 'port', 'auth', 'path'); const proxyInfo = JSON.stringify(obj, null, '\t'); console.log(`Proxying request through ${proxyInfo}`); } req.proxy(config.proxy); } req.end((err, res) => { if (err) { if (err.status >= 400 && res.body.error) { reject(new Error(res.body.error)); return; } reject(err); return; } const result = res.headers['content-type'] && res.headers['content-type'].match(/^application\/json/) ? res.body : res.text; if (!jwt) { resolve(result); return; } loadConfig() .then(c => { const conf = c; // stupid eslint rule! conf.jwt = res.headers['x-jwt']; return saveConfig(conf); }) .then(() => resolve(result)) .catch(reject); }); }); } export default function request(method, path, payload, auth, app) { if (auth) { return loadConfig().then(conf => exec(method, path, payload, conf.jwt, app)); } return exec(method, path, payload, null, app); }