jquery.ajax-retry.js 2.43 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/*
 * jquery.ajax-retry
 * https://github.com/johnkpaul/jquery-ajax-retry
 *
 * Copyright (c) 2012 John Paul
 * Licensed under the MIT license.
 */
(function(factory) {
    if (typeof define === 'function' && define.amd) {
      // AMD. Register as an anonymous module.
      define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        factory(require('jquery'));
    } else {
      // Browser globals
      factory(jQuery);
    }
})(function($) {

  // enhance all ajax requests with our retry API
  $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    jqXHR.retry = function(opts) {
      if(opts.timeout) {
        this.timeout = opts.timeout;
      }
      if (opts.statusCodes) {
        this.statusCodes = opts.statusCodes;
      }
      return this.pipe(null, pipeFailRetry(this, opts));
    };
  });

  // generates a fail pipe function that will retry `jqXHR` `times` more times
  function pipeFailRetry(jqXHR, opts) {
    var times = opts.times;
    var timeout = jqXHR.timeout;

    // takes failure data as input, returns a new deferred
    return function(input, status, msg) {
      var ajaxOptions = this;
      var output = new $.Deferred();
      var retryAfter = jqXHR.getResponseHeader('Retry-After');

      // whenever we do make this request, pipe its output to our deferred
      function nextRequest() {
        $.ajax(ajaxOptions)
          .retry({times: times - 1, timeout: opts.timeout})
          .pipe(output.resolve, output.reject);
      }

      if (times > 1 && (!jqXHR.statusCodes || $.inArray(input.status, jqXHR.statusCodes) > -1)) {
        // implement Retry-After rfc
        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.37
        if (retryAfter) {
          // it must be a date
          if (isNaN(retryAfter)) {
            timeout = new Date(retryAfter).getTime() - $.now();
          // its a number in seconds
          } else {
            timeout = parseInt(retryAfter, 10) * 1000;
          }
          // ensure timeout is a positive number
          if (isNaN(timeout) || timeout < 0) {
            timeout = jqXHR.timeout;
          }
        }

        if (timeout !== undefined){
          setTimeout(nextRequest, timeout);
        } else {
          nextRequest();
        }
      } else {
        // no times left, reject our deferred with the current arguments
        output.rejectWith(this, arguments);
      }

      return output;
    };
  }

});