From b43dbd432c129c1606b883db83a9092dca49e522 Mon Sep 17 00:00:00 2001 From: Peng Xia Date: Thu, 10 Jan 2019 13:46:27 -0800 Subject: [PATCH] Add support for http and https proxy --- lib/wit.js | 26 ++++++++++++++++++++++---- package.json | 1 + 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/lib/wit.js b/lib/wit.js index cab92f7..73a6c10 100644 --- a/lib/wit.js +++ b/lib/wit.js @@ -11,16 +11,32 @@ const { } = require('./config'); const fetch = require('isomorphic-fetch'); const log = require('./log'); +const Url = require('url'); +const HttpsProxyAgent = require('https-proxy-agent'); const learnMore = 'Learn more at https://wit.ai/docs/quickstart'; +function getProxyAgent(witURL) { + const url = Url.parse(witURL); + const proxy = url.protocol === "http:" ? + process.env.http_proxy || process.env.HTTP_PROXY : + process.env.https_proxy || process.env.HTTPS_PROXY; + const noProxy = process.env.no_proxy || process.env.NO_PROXY; + + const shouldIgnore = noProxy && noProxy.indexOf(url.hostname) > -1; + if (proxy && !shouldIgnore) { + return new HttpsProxyAgent(proxy); + } + if(!proxy) return null; +} + function Wit(opts) { if (!(this instanceof Wit)) { return new Wit(opts); } const { - accessToken, apiVersion, headers, logger, witURL + accessToken, apiVersion, headers, logger, witURL, proxy } = this.config = Object.freeze(validate(opts)); this._sessions = {}; @@ -46,10 +62,11 @@ function Wit(opts) { return fetch(fullURL, { method, headers, + proxy, }) - .then(response => Promise.all([response.json(), response.status])) - .then(handler) - ; + .then(response => Promise.all([response.json(), response.status])) + .then(handler) + ; }; } @@ -93,6 +110,7 @@ const validate = (opts) => { 'Content-Type': 'application/json', }; opts.logger = opts.logger || new log.Logger(log.INFO); + opts.proxy = getProxyAgent(opts.witURL); return opts; }; diff --git a/package.json b/package.json index 91b4665..3b74628 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "dependencies": { "body-parser": "^1.18.2", "express": "^4.16.2", + "https-proxy-agent": "^1.0.0", "isomorphic-fetch": "^2.2.1", "request": "^2.83.0", "uuid": "^3.0.0"