diff --git a/lib/wit.js b/lib/wit.js index 1c1bc3b..eafd327 100644 --- a/lib/wit.js +++ b/lib/wit.js @@ -3,8 +3,10 @@ const fetch = require('node-fetch'); const readline = require('readline'); const uuid = require('node-uuid'); +const Url = require('url'); const Logger = require('./logger').Logger; const logLevels = require('./logger').logLevels; +const HttpsProxyAgent = require('https-proxy-agent'); const DEFAULT_API_VERSION = '20160516'; const DEFAULT_MAX_STEPS = 5; @@ -59,7 +61,7 @@ const validateActions = (actions) => { if (!actions.error) { throw new Error('The \'error\' action is missing. ' + learnMore); } - + Object.keys(actions).forEach(key => { if (typeof actions[key] !== 'function') { l.warn('The \'' + key + '\' action should be a function.'); @@ -109,9 +111,24 @@ const clone = (obj) => { } }; +const getProxyAgent = (wit_url) => { + const url = Url.parse(wit_url); + 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; +}; + const Wit = function(token, actions, logger) { const baseURL = process.env.WIT_URL || 'https://api.wit.ai'; const version = process.env.WIT_API_VERSION || DEFAULT_API_VERSION; + const proxyAgent = getProxyAgent(baseURL); const headers = { 'Authorization': 'Bearer ' + token, 'Accept': 'application/vnd.wit.' + version + '+json', @@ -135,6 +152,7 @@ const Wit = function(token, actions, logger) { fetch(baseURL + '/message?' + qs, { method: 'GET', headers: headers, + agent: proxyAgent }) .then(response => Promise.all([response.json(), response.status])) .then(handler) @@ -152,6 +170,7 @@ const Wit = function(token, actions, logger) { method: 'POST', headers: headers, body: JSON.stringify(context), + agent: proxyAgent }) .then(response => Promise.all([response.json(), response.status])) .then(handler) diff --git a/package.json b/package.json index d5bbf08..2c70be0 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "repository": "https://github.com/wit-ai/node-wit", "author": "Julien Odent ", "dependencies": { + "https-proxy-agent": "^1.0.0", "node-fetch": "^1.5.1", "node-uuid": "^1.4.7" }