Skip to content

Instantly share code, notes, and snippets.

@wholypantalones
Created July 13, 2017 15:39
Show Gist options
  • Save wholypantalones/89ddafdd0d8bb6f0c7d96dd1eaa4b2e7 to your computer and use it in GitHub Desktop.
Save wholypantalones/89ddafdd0d8bb6f0c7d96dd1eaa4b2e7 to your computer and use it in GitHub Desktop.
http-queue
'use strict';
/* config provide */
/* ignores unhandled rejection for cancelled in Angular 1.6 */
/* */
/* http requests middleware service */
/* if no groupingId is specified, each req is a duplicate by default */
/* usage: */
/* httpQueueService.add(useThisFunction, {timeout: 1000, groupingId:'myCustomQueue'}); */
/* usage with params: */
/* httpQueueService.add(function(){updateCart(product,qty),{timeout:300, groupingId:'cart'}} */
/* Global config: */
/* httpQueueService.configure({timeout: 1000}, 'myCustomQueue'); */
angular.module('retailApp')
.config(['$provide', function ($provide) {
$provide.decorator("$exceptionHandler", ['$delegate', '$injector', function ($delegate, $injector) {
return function (exception, cause) {
var exceptionsToIgnore = ['Possibly unhandled rejection: canceled'];
if (exceptionsToIgnore.indexOf(exception) >= 0) {
return;
}
$delegate(exception, cause);
};
}]);
}])
.factory('httpQueueService', function ($timeout) {
var defaultQueueName = 'default';
var queue = [];
var queueConfig = {};
queueConfig[defaultQueueName] = {timeout: 0};
function isDuplicate(queueItem, callback, options) {
if (null != options.groupingId || null != queueItem.options.groupingId) {
return options.groupingId === queueItem.options.groupingId;
}
return queueItem.callback === callback;
}
function createQueueItem(callback, config, options) {
config = angular.extend({}, config, options);
var promise = $timeout(callback, config.timeout);
promise.then(function removeQueueItem() {
for (var i = 0; i < queue.length; i++) {
if (queue[i].promise === promise) {
queue.splice(i, 1);
return;
}
}
});
return {callback: callback, options: options, promise: promise};
}
function add(callback, options) {
options = angular.extend({queueId: defaultQueueName}, options);
for (var i = 0; i < queue.length; i++) {
if (isDuplicate(queue[i], callback, options)) {
$timeout.cancel(queue[i].promise);
queue.splice(i, 1);
break;
}
}
if (null == queueConfig[options.queueId]) {
console.warn('No queue "' + options.queueId + '" defined');
options.queueId = defaultQueueName;
}
var config = angular.extend({}, queueConfig[options.queueId], options);
if (config.timeout > 0) {
queue.push(createQueueItem(callback, config, options));
} else {
callback();
}
}
function configure(config, queueId) {
if (null == queueId) {
queueId = defaultQueueName;
}
queueConfig[queueId] = angular.extend(queueConfig[queueId] || {}, config);
}
return {
add: add,
configure: configure
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment