Files
notifications-admin/app/assets/javascripts/updateContent.js
Chris Hill-Scott 940170159a Handle AJAX errors when updating content
With the change in implementation in the previous commit, any error
(eg server responds with `500`) would cause the page to not be updated
again.

This is better than the previous implementation, whereby the browser
would re-request as fast as it could until it got a successful response.

This commit handles errors by clearing the render queue if the server
returns an error. So:

- Any updates that would have been performed based on this request are
  dropped
- Subsequent updates will be attempted as if it was the first load of
  the page, ie after a delay of `x` seconds
2016-06-12 14:16:27 +01:00

50 lines
1.0 KiB
JavaScript

(function(Modules) {
"use strict";
var queues = {};
var dd = new diffDOM();
var getRenderer = $component => response => dd.apply(
$component.get(0),
dd.diff($component.get(0), $(response[$component.data('key')]).get(0))
);
var getQueue = resource => (
queues[resource] = queues[resource] || []
);
var flushQueue = function(queue, response) {
while(queue.length) queue.shift()(response);
};
var clearQueue = queue => (queue.length = 0);
var poll = function(renderer, resource, queue, interval) {
if (queue.push(renderer) === 1) $.ajax(
resource
).done(
response => flushQueue(queue, response)
).fail(
() => clearQueue(queue)
);
setTimeout(
() => poll(...arguments), interval
);
};
Modules.UpdateContent = function() {
this.start = component => poll(
getRenderer($(component)),
$(component).data('resource'),
getQueue($(component).data('resource')),
($(component).data('interval-seconds') || 1.5) * 1000
);
};
})(window.GOVUK.Modules);