queued-http.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* eslint-disable
  2. max-len,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS101: Remove unnecessary use of Array.from
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS207: Consider shorter variations of null checks
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. import App from '../base'
  14. export default App.factory('queuedHttp', [
  15. '$http',
  16. function ($http) {
  17. const pendingRequests = []
  18. let inflight = false
  19. function processPendingRequests() {
  20. if (inflight) {
  21. return
  22. }
  23. const doRequest = pendingRequests.shift()
  24. if (doRequest != null) {
  25. inflight = true
  26. return doRequest()
  27. .then(function () {
  28. inflight = false
  29. return processPendingRequests()
  30. })
  31. .catch(function () {
  32. inflight = false
  33. return processPendingRequests()
  34. })
  35. }
  36. }
  37. const queuedHttp = function (...args) {
  38. // We can't use Angular's $q.defer promises, because it only passes
  39. // a single argument on error, and $http passes multiple.
  40. const promise = {}
  41. const successCallbacks = []
  42. const errorCallbacks = []
  43. // Adhere to the $http promise conventions
  44. promise.then = function (callback, errCallback) {
  45. successCallbacks.push(callback)
  46. if (errCallback != null) {
  47. errorCallbacks.push(errCallback)
  48. }
  49. return promise
  50. }
  51. promise.catch = function (callback) {
  52. errorCallbacks.push(callback)
  53. return promise
  54. }
  55. const doRequest = () =>
  56. $http(...Array.from(args || []))
  57. .then((...args) =>
  58. Array.from(successCallbacks).map(fn =>
  59. fn(...Array.from(args || []))
  60. )
  61. )
  62. .catch((...args) =>
  63. Array.from(errorCallbacks).map(fn => fn(...Array.from(args || [])))
  64. )
  65. pendingRequests.push(doRequest)
  66. processPendingRequests()
  67. return promise
  68. }
  69. queuedHttp.post = (url, data) => queuedHttp({ method: 'POST', url, data })
  70. return queuedHttp
  71. },
  72. ])