Skip to content

Instantly share code, notes, and snippets.

@leewinder
Created September 3, 2016 06:32
Show Gist options
  • Save leewinder/b9b477fb4296a36b80a593407739d0de to your computer and use it in GitHub Desktop.
Save leewinder/b9b477fb4296a36b80a593407739d0de to your computer and use it in GitHub Desktop.
JavaScript object to call authorised AWS functions and automatically retry failed calls multiple times
"use strict";
//
// Class to call and retry AWS requests
//
var AwsRequest = (function () {
//
// Constructor
//
function AwsRequest(retryCount, retryDelay) {
// Set some default values
if (retryCount == null) {
retryCount = this.DEFAULT_RETRY_COUNT();
}
if (retryDelay == null) {
retryDelay = this.DEFAULT_RETRY_DELAY_MILLISECONDS();
}
// Save our retry counts
this.retryCount = retryCount;
this.retryDelay = retryDelay;
}
// Properties
AwsRequest.prototype.DEFAULT_RETRY_COUNT = function () { return 3; };
AwsRequest.prototype.DEFAULT_RETRY_DELAY_MILLISECONDS = function () { return 1000; };
//
// Requests a call to an AWS function
//
AwsRequest.prototype.request = function (params, service, functionRequest, completedCallback, successCallback, errorCallback) {
// Kick off the request
this.__runRequest(this, 0, params, service, functionRequest, completedCallback, successCallback, errorCallback);
};
//
// Triggers the run request and runs it multiple times if needed
//
AwsRequest.prototype.__runRequest = function (self, callbackCount, params, service, functionRequest, completedCallback, successCallback, errorCallback) {
// Bypass, and make our requests directly so
service.makeRequest(functionRequest, params, function (error, data) {
if (error) {
// Call the error callback so we can display valid information before dumping the stack
if (errorCallback !== null) {
var updatedParams = errorCallback(error, params);
if (updatedParams != null) {
params = updatedParams;
}
}
console.log(error, error.stack);
// Do we need to try again?
++callbackCount;
if (callbackCount < self.retryCount) {
// Try again after a given delay
setTimeout(function () {
self.__runRequest(self, callbackCount, params, service, functionRequest, completedCallback, successCallback, errorCallback);
}, self.retryDelay);
} else {
// We failed, so send it back
completedCallback(error, null);
}
} else {
// We're done, so send the data back
if (successCallback !== null) {
successCallback(data);
}
completedCallback(null, data);
}
});
};
// Object creation
return AwsRequest;
} ());
// Available exports
exports.AwsRequest = AwsRequest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment