diff --git a/package.json b/package.json index 1d9ccefe..ab8db448 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,8 @@ "http_ece": "^0.5.2", "jws": "^3.1.3", "minimist": "^1.2.0", + "request": "^2.81.0", + "request-promise-native": "^1.0.4", "urlsafe-base64": "^1.0.0" }, "devDependencies": { diff --git a/src/web-push-lib.js b/src/web-push-lib.js index d19c5adc..9220f994 100644 --- a/src/web-push-lib.js +++ b/src/web-push-lib.js @@ -2,7 +2,7 @@ const urlBase64 = require('urlsafe-base64'); const url = require('url'); -const https = require('https'); +const request = require('request-promise-native'); const WebPushError = require('./web-push-error.js'); const vapidHelper = require('./vapid-helper.js'); @@ -254,45 +254,32 @@ WebPushLib.prototype.sendNotification = } return new Promise(function(resolve, reject) { - const httpsOptions = {}; - const urlParts = url.parse(requestDetails.endpoint); - httpsOptions.hostname = urlParts.hostname; - httpsOptions.port = urlParts.port; - httpsOptions.path = urlParts.path; + const httpsOptions = { + uri: requestDetails.endpoint, + headers: requestDetails.headers, + method: requestDetails.method, + resolveWithFullResponse: true + }; - httpsOptions.headers = requestDetails.headers; - httpsOptions.method = requestDetails.method; - - const pushRequest = https.request(httpsOptions, function(pushResponse) { - let responseText = ''; - - pushResponse.on('data', function(chunk) { - responseText += chunk; - }); + if (requestDetails.body) { + httpsOptions.method = 'POST'; + httpsOptions.body = requestDetails.body; + } - pushResponse.on('end', function() { + return request(httpsOptions) + .then((pushResponse) => { if (pushResponse.statusCode !== 201) { - reject(new WebPushError('Received unexpected response code', - pushResponse.statusCode, pushResponse.headers, responseText, requestDetails.endpoint)); - } else { - resolve({ - statusCode: pushResponse.statusCode, - body: responseText, - headers: pushResponse.headers - }); + return reject(new WebPushError('Received unexpected response code', + pushResponse.statusCode, pushResponse.headers, pushResponse.body, subscription.endpoint)); } - }); - }); - - pushRequest.on('error', function(e) { - reject(e); - }); - - if (requestDetails.body) { - pushRequest.write(requestDetails.body); - } - pushRequest.end(); + return resolve({ + statusCode: pushResponse.statusCode, + body: pushResponse.body, + headers: pushResponse.headers + }); + }) + .catch(reject); }); };