Created
August 14, 2015 20:49
-
-
Save justinwinslow/4f7ac44251002164cf80 to your computer and use it in GitHub Desktop.
Angular - Prevent duplicate $http GETs from firing at the same time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$provide.decorator('$http', ['$delegate', function($delegate) { | |
// Angular injects the service as $delegate | |
var $http = $delegate; | |
// Store promises for requests | |
var pendingRequests = []; | |
// Let's overwrite the get method to prevent duplicate queries | |
$http.get = function (url, config) { | |
config = config || {}; | |
// Let's make a simple key for us to reference on subsequent requests | |
// NOTE - if the request has a timeout, deduping can result | |
// in no one getting their response, so let's make the id unique | |
var unique = (config.timeout) ? Date.now() : ''; | |
var id = url + JSON.stringify(config.params || {}) + unique; | |
// See if there is already a promise for that particular key | |
// and return it if there is | |
var pendingRequest = _.find(pendingRequests, {id: id}); | |
if (pendingRequest) { | |
return pendingRequest.promise; | |
} | |
// Do the request | |
var promise = $http(angular.extend({}, config || {}, { | |
method: 'get', | |
url: url | |
})); | |
// Let's set pendingRequest to a new object with our new promise | |
pendingRequest = { | |
id: id, | |
promise: promise | |
}; | |
// Add the promise to the pending requests array | |
pendingRequests.push(pendingRequest); | |
promise.finally(function(){ | |
// Get rid of the reference when the promise is satisfied | |
pendingRequests.splice(pendingRequests.indexOf(pendingRequest), 1); | |
}); | |
return promise; | |
}; | |
return $http; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment