Last active
December 29, 2017 19:26
-
-
Save rothlis/78c37724e4aaa56ef9a4ddc1a3c8c945 to your computer and use it in GitHub Desktop.
AngularJS decorator to prevent identical request
This file contains hidden or 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
| const $duplicateRequestDecorator = ($delegate, $q) => { | |
| const pendingRequestPromises = {} | |
| function $http(config) { | |
| if (config.ignoreDuplicateRequest) { | |
| return $delegate(config) | |
| } | |
| let identifier = getRequestIdentifier(config) | |
| if (pendingRequestPromises[identifier]) { | |
| if (config.rejectDuplicateRequest) { | |
| return $q.reject({ | |
| data: '', | |
| headers: {}, | |
| status: config.rejectDuplicateStatusCode || 400, | |
| config: config, | |
| }) | |
| } | |
| return $q.defer().promise | |
| } | |
| pendingRequestPromises[identifier] = $delegate(config).finally(() => { | |
| delete pendingRequestPromises[identifier] | |
| }) | |
| return pendingRequestPromises[identifier] | |
| } | |
| Object.keys($delegate) | |
| .filter(key => angular.isFunction($delegate[key])) | |
| .forEach(key => ($http[key] = $delegate[key])) | |
| return $http | |
| } | |
| function hash(string) { | |
| let hash = 0 | |
| if (string.length === 0) return hash | |
| for (let i = 0, charCode; i < string.length; ++i) { | |
| charCode = string.charCodeAt(i) | |
| hash = (hash << 5) - hash + charCode | |
| hash = hash & hash | |
| } | |
| return hash >>> 0 | |
| } | |
| function getRequestIdentifier(config) { | |
| let string = config.method + config.url | |
| if (angular.isObject(config.params)) { | |
| string += angular.toJson(config.params) | |
| } | |
| if (angular.isObject(config.data)) { | |
| string += angular.toJson(config.data) | |
| } | |
| return hash(string) | |
| } | |
| $duplicateRequestDecorator.$inject = ['$delegate', '$q'] | |
| angular.module('shared').decorator('$http', $duplicateRequestDecorator) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment