From 1274b1ce4745a37d590ba9503035111d0e86fb93 Mon Sep 17 00:00:00 2001 From: Christian Holm Date: Thu, 11 Jan 2018 13:01:17 +0100 Subject: [PATCH] Add support for custom timeout setting (#176) * Add support for custom timeout setting * Document new option parameter --- README.md | 4 +++- src/HttpClient.js | 7 ++++++- test/HttpClient-test.js | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9b01a35e..1f71c663 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,9 @@ Options are: log: function() {level, args...} info: function() {args...}, warn: function() {args...} - } + }, + // Set a custom timeout for requests to Nexmo in milliseconds. Defaults to the standard for Node http requests, which is 120,000 ms. + timeout: integer } ``` diff --git a/src/HttpClient.js b/src/HttpClient.js index 32a01100..11a9e791 100644 --- a/src/HttpClient.js +++ b/src/HttpClient.js @@ -14,6 +14,7 @@ class HttpClient { Accept: "application/json" }; this.logger = options.logger; + this.timeout = options.timeout; if (options.userAgent) { this.headers["User-Agent"] = options.userAgent; @@ -42,6 +43,10 @@ class HttpClient { headers: Object.assign({}, this.headers) }; + if (this.timeout !== undefined) { + options.timeout = this.timeout; + } + // Allow existing headers to be overridden // Allow new headers to be added if (endpoint.headers) { @@ -56,7 +61,7 @@ class HttpClient { if (options.port === 443) { request = this.https.request(options); } else { - request = http.request(options); + request = this.http.request(options); } request.end(endpoint.body); diff --git a/test/HttpClient-test.js b/test/HttpClient-test.js index c89e5e07..9ff942e9 100644 --- a/test/HttpClient-test.js +++ b/test/HttpClient-test.js @@ -189,6 +189,39 @@ describe("HttpClient Object", function() { ); }); + it("should be possible to set the timeout", function() { + var mock = sinon.mock(fakeHttp); + mock + .expects("request") + .once() + .withArgs({ + headers: defaultHeaders, + host: "api.nexmo.com", + method: "POST", + path: "/api", + port: 443, + timeout: 5000 + }) + .returns(fakeRequest); + + var client = new HttpClient({ + https: fakeHttp, + logger: logger, + timeout: 5000 + }); + + client.request( + { + host: "api.nexmo.com", + path: "/api" + }, + "POST", + { + some: "data" + } + ); + }); + it("should not override the method when method and callback are undefined", function() { var mock = sinon.mock(fakeHttp); mock