From 90ca4ebb6e0e6b59bd554908105f66114ad5a8f6 Mon Sep 17 00:00:00 2001 From: Andrei Cioban Date: Thu, 19 Oct 2017 20:32:19 +0300 Subject: [PATCH] Added maxSockets support. --- lib/client.js | 13 ++++++++++++- test/test.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/lib/client.js b/lib/client.js index 8f59367..78d98c3 100644 --- a/lib/client.js +++ b/lib/client.js @@ -27,9 +27,16 @@ var response = { } // Client allows for quick and easy access any REST or REST-like API. -function Client (globalRequest) { +function Client (globalRequest, maxSockets) { var emptyResponse = JSON.parse(JSON.stringify(response)) var body = '' + var httpAgent = null; + var httpsAgent = null; + + if(maxSockets) { + httpAgent = new http.Agent({ maxSockets: maxSockets }); + httpsAgent = new https.Agent({ maxSockets: maxSockets }); + } // utility function to create an empty request object this.emptyRequest = function () { @@ -81,6 +88,10 @@ function Client (globalRequest) { request.headers['Content-Type'] = 'application/json' } + //if maxsockets where provided use the apropriate agent + if(maxSockets) { + request.agent = endpointRequest.test == true ? httpAgent : httpsAgent + } return request } diff --git a/test/test.js b/test/test.js index 989d304..490456b 100644 --- a/test/test.js +++ b/test/test.js @@ -209,4 +209,35 @@ describe('Client', function () { }) }) }) + + // limit maxSockets + describe('#API()', function () { + it('should limit maxSockets', function (done) { + var expectedSockets = 10 + var maxSocketsClient = new Client(globalRequest, expectedSockets) + + nock(TEST_HOST) + .get('/testMax') + .reply(200) + + // monkey patch the http.request + var http = require('http') + var originalRequest = http.request + http.request = function(options, callback){ + assert.isDefined(options.agent, 'the request should use a custom agent'); + assert.equal(options.agent.maxSockets, expectedSockets, 'agent.maxSockets should equal expectedSockets') + return originalRequest(options, callback) + } + + var requestGet = maxSocketsClient.emptyRequest() + requestGet.method = 'GET' + requestGet.test = true + requestGet.path = '/testMax' + maxSocketsClient.API(requestGet, function (response) { + //restore the opriginal request + http.request = originalRequest + done() + }) + }) + }) })