Skip to content

Instantly share code, notes, and snippets.

@hongster
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongster/f0686c927c128e1567b7 to your computer and use it in GitHub Desktop.
Save hongster/f0686c927c128e1567b7 to your computer and use it in GitHub Desktop.
Simple AJAX call helper, with lock mechanism to prevent duplicated concurrent connections. It sends data in JSON format, you can easily adapt it to to your need. Dependencies: jQuery ($.ajax) and UnderscoreJS. You can easily remove UnderscoreJS code.
/**
* Simple AJAX call helper, with lock mechanism to prevent duplicated concurrent connections.
* It sends data in JSON format, you can easily adapt it to to your need.
* Dependencies: jQuery ($.ajax) and UnderscoreJS. You can easily remove UnderscoreJS code.
*/
var API = new function() {
var self = this;
// Lock to prevent duplicated concurrent API calls.
self.locks = {};
/**
* @param string uri E.g. login
* @return string API URL
*/
self.endpoint = function(uri) {
return 'http://example.com' + uri;
};
/**
* Simple lock mechanism to prevent concurrent duplicated calls.
* @param string name Unique name for AJAX call. E.g. "login"
* @return bool If true, proceed to perform AJAX call.
*/
self.accquireAJAX = function(name) {
if (!_.has(self.locks, name))
self.locks[name] = 0;
// Release lock after 3 minutes
var now = new Date().getTime(); // Timestamp in milliseconds
if (now - self.locks[name] > 180000) {
self.locks[name] = now;
return true;
}
return false;
};
/**
* Simple lock mechanism to prevent concurrent duplicated calls.
* @param {string} name Unique name for AJAX call. E.g. "login"
*/
self.releaseAJAX = function(name) {
self.locks[name] = 0;
};
/**
* Log AJAX response.
* @param {objext} context AJAX context
*/
self.ajaxLogger = function(context) {
console.log(context);
};
/**
* Perform API call.
* @param {string} uri
* @param {JSON} options Key-value pair parameters
* @param {callback} success Optional.
* @param {callback} error Optional.
*/
self.call = function(uri, options, success, error) {
if (!self.accquireAJAX(uri))
return;
console.log('Calling ' + uri);
success = _.isUndefined(success) ? self.ajaxLogger : success;
error = _.isUndefined(error) ? self.ajaxLogger : error;
var data = JSON.stringify(options);
$.ajax({
url: self.endpoint(uri),
type: 'POST',
contentType: 'application/json',
data: data,
success: success,
error: error,
complete: function() {
self.releaseAJAX(uri);
console.log('Completed ' + uri);
}
});
};
}; // API
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment