Skip to content

Commit

Permalink
Replace request with axios (#372) (thanks @pmb-cl)
Browse files Browse the repository at this point in the history
* replace request with axios

* bumping pkg version

* changes for axios

* fixed tests

* small update to comment

* putting test back

* using a tilda for axios version

* compiled in nodev12
  • Loading branch information
pmb-cl authored Sep 21, 2023
1 parent d5cfe6a commit 42afc1b
Show file tree
Hide file tree
Showing 4 changed files with 226 additions and 581 deletions.
60 changes: 34 additions & 26 deletions lib/sender.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var Constants = require('./constants');
var _ = require('lodash');
var request = require('request');
var request = require('axios');
var debug = require('debug')('node-gcm');

function Sender(key, options) {
Expand Down Expand Up @@ -147,36 +147,44 @@ Sender.prototype.sendNoRetry = function(message, recipient, callback) {
method: 'POST',
headers: {
'Authorization': 'key=' + this.key
},
json: body
}
}, this.options, {
uri: Constants.GCM_SEND_URI,
timeout: Constants.SOCKET_TIMEOUT
});

request(request_options, function (err, res, resBodyJSON) {
if (err) {
// overloading the post function to make testing it easier
request.post(request_options.uri || Constants.GCM_SEND_URI, body, request_options, callback)
.then((res) => {
const { data: resBodyJSON, status } = res;

if (status !== 200) {
debug('Invalid request (' + status + '): ' + resBodyJSON);
return callback(status);
}

if (_.isEmpty(resBodyJSON)) {
debug('Empty response received (' + status + ' ' + res.statusText + ')');
// Spoof error code 400 to avoid retrying the request
return callback({error: res.statusText, code: 400});
}

callback(null, resBodyJSON, body.registration_ids || [ body.to ]);
},
(err) => {
const { response: res } = err;

if (res.status === 401) {
debug('Unauthorized (401). Check that your API token is correct.');
return callback(res.status);
}

if (res.status >= 500) {
debug('GCM service is unavailable (500)');
return callback(res.status);
}

return callback(err);
}
if (res.statusCode >= 500) {
debug('GCM service is unavailable (500)');
return callback(res.statusCode);
}
if (res.statusCode === 401) {
debug('Unauthorized (401). Check that your API token is correct.');
return callback(res.statusCode);
}
if (res.statusCode !== 200) {
debug('Invalid request (' + res.statusCode + '): ' + resBodyJSON);
return callback(res.statusCode);
}
if (!resBodyJSON) {
debug('Empty response received (' + res.statusCode + ' ' + res.statusMessage + ')');
// Spoof error code 400 to avoid retrying the request
return callback({error: res.statusMessage, code: 400});
}
callback(null, resBodyJSON, body.registration_ids || [ body.to ]);
});
});
}.bind(this));
};

Expand Down
Loading

0 comments on commit 42afc1b

Please sign in to comment.