All files / node-request-retry index.js

100% Statements 111/111
100% Branches 60/60
100% Functions 23/23
100% Lines 110/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254                  1x 1x 1x 1x 1x   1x                 13x                             21x 21x     21x         43x   6x 2x     6x 2x       6x     43x 37x 19x   37x     43x 43x 43x 43x           43x           43x           43x   43x 43x   43x     43x 21x     43x 44x 22x     22x 3x       19x 19x       1x   1x 53x 53x   53x 51x 47x     51x 4x     51x 51x 6x 3x   6x     51x 10x 10x     41x       1x 3x 2x   3x 3x       1x 10x 2x         1x 5x 21x 1x   20x         43x 43x 43x 43x         54x   10x   6x 2x     6x 2x       6x     10x 4x 2x   4x     10x 10x         8x 6x 2x   6x     8x 2x     8x 8x   8x 48x   8x   8x 16x     8x     1x   1x 1x 1x     1x 6x   1x   1x 2x    
'use strict';
 
/*
 * Request
 *
 * Copyright(c) 2014 Francois-Guillaume Ribreau <npm@fgribreau.com>
 * MIT Licensed
 *
 */
var extend = require('extend');
var when = require('when');
var request = require('request');
var RetryStrategies = require('./strategies');
var _ = require('lodash');
 
var DEFAULTS = {
  maxAttempts: 5, // try 5 times
  retryDelay: 5000, // wait for 5s before trying again
  fullResponse: true, // resolve promise with the full response object
  promiseFactory: defaultPromiseFactory // Function to use a different promise implementation library
};
 
// Default promise factory which use bluebird
function defaultPromiseFactory(resolver) {
  return when.promise(resolver);
}
 
/**
 * It calls the promiseFactory function passing it the resolver for the promise
 *
 * @param {Object} requestInstance - The Request Retry instance
 * @param {Function} promiseFactoryFn - The Request Retry instance
 * @return {Object} - The promise instance
 */
function makePromise(requestInstance, promiseFactoryFn) {
 
  // Resolver function wich assigns the promise (resolve, reject) functions
  // to the requestInstance
  function Resolver(resolve, reject) {
    this._resolve = resolve;
    this._reject = reject;
  }
 
  return promiseFactoryFn(Resolver.bind(requestInstance));
}
 
function Request(url, options, f, retryConfig) {
  // ('url')
  if(_.isString(url)){
    // ('url', f)
    if(_.isFunction(options)){
      f = options;
    }
 
    if(!_.isObject(options)){
      options = {};
    }
 
    // ('url', {object})
    options.url = url;
  }
 
  if(_.isObject(url)){
    if(_.isFunction(options)){
      f = options;
    }
    options = url;
  }
 
  this.maxAttempts = retryConfig.maxAttempts;
  this.retryDelay = retryConfig.retryDelay;
  this.fullResponse = retryConfig.fullResponse;
  this.attempts = 0;
 
  /**
   * Option object
   * @type {Object}
   */
  this.options = options;
 
  /**
   * Return true if the request should be retried
   * @type {Function} (err, response, body, options) -> [Boolean, Object (optional)]
   */
  this.retryStrategy = _.isFunction(options.retryStrategy) ? options.retryStrategy : RetryStrategies.HTTPOrNetworkError;
 
  /**
   * Return a number representing how long request-retry should wait before trying again the request
   * @type {Boolean} (err, response, body) -> Number
   */
  this.delayStrategy = _.isFunction(options.delayStrategy) ? options.delayStrategy : function() { return this.retryDelay; };
 
  this._timeout = null;
  this._req = null;
 
  this._callback = _.isFunction(f) ? _.once(f) : null;
 
  // create the promise only when no callback was provided
  if (!this._callback) {
    this._promise = makePromise(this, retryConfig.promiseFactory);
  }
 
  this.reply = function requestRetryReply(err, response, body) {
    if (this._callback) {
      return this._callback(err, response, body);
    }
 
    if (err) {
      return this._reject(err);
    }
 
    // resolve with the full response or just the body
    response = this.fullResponse ? response : body;
    this._resolve(response);
  };
}
 
Request.request = request;
 
Request.prototype._tryUntilFail = function () {
  this.maxAttempts--;
  this.attempts++;
 
  this._req = Request.request(this.options, function (err, response, body) {
    if (response) {
      response.attempts = this.attempts;
    }
 
    if (err) {
      err.attempts = this.attempts;
    }
 
    var mustRetry = this.retryStrategy(err, response, body, _.cloneDeep(this.options));
    if (_.isObject(mustRetry)) {
      if (_.isObject(mustRetry.options)) {
        this.options = mustRetry.options; //if retryStrategy supposes different request options for retry
      }
      mustRetry = mustRetry.mustRetry;
    }
 
    if (mustRetry && this.maxAttempts > 0) {
      this._timeout = setTimeout(this._tryUntilFail.bind(this), this.delayStrategy.call(this, err, response, body));
      return;
    }
 
    this.reply(err, response, body);
  }.bind(this));
};
 
Request.prototype.abort = function () {
  if (this._req) {
    this._req.abort();
  }
  clearTimeout(this._timeout);
  this.reply(new Error('Aborted'));
};
 
// expose request methods from RequestRetry
['end', 'on', 'emit', 'once', 'setMaxListeners', 'start', 'removeListener', 'pipe', 'write', 'auth'].forEach(function (requestMethod) {
  Request.prototype[requestMethod] = function exposedRequestMethod () {
    return this._req[requestMethod].apply(this._req, arguments);
  };
});
 
// expose promise methods
['then', 'catch', 'finally', 'fail', 'done'].forEach(function (promiseMethod) {
  Request.prototype[promiseMethod] = function exposedPromiseMethod () {
    if (this._callback) {
      throw new Error('A callback was provided but waiting a promise, use only one pattern');
    }
    return this._promise[promiseMethod].apply(this._promise, arguments);
  };
});
 
function Factory(url, options, f) {
  var retryConfig = _.chain(_.isObject(url) ? url : options || {}).defaults(DEFAULTS).pick(Object.keys(DEFAULTS)).value();
  var req = new Factory.Request(url, options, f, retryConfig);
  req._tryUntilFail();
  return req;
}
 
// adds a helper for HTTP method `verb` to object `obj`
function makeHelper(obj, verb) {
  obj[verb] = function helper(url, options, f) {
    // ('url')
    if(_.isString(url)){
      // ('url', f)
      if(_.isFunction(options)){
        f = options;
      }
 
      if(!_.isObject(options)){
        options = {};
      }
 
      // ('url', {object})
      options.url = url;
    }
 
    if(_.isObject(url)){
      if(_.isFunction(options)){
        f = options;
      }
      options = url;
    }
 
    options.method = verb.toUpperCase();
    return obj(options, f);
  };
}
 
function defaults(defaultOptions, defaultF) {
  var factory = function (options, f) {
    if (typeof options === "string") {
      options = { uri: options };
    }
    return Factory.apply(null, [ extend(true, {}, defaultOptions, options), f || defaultF ]);
  };
 
  factory.defaults = function (newDefaultOptions, newDefaultF) {
    return defaults.apply(null, [ extend(true, {}, defaultOptions, newDefaultOptions), newDefaultF || defaultF ]);
  };
 
  factory.Request = Request;
  factory.RetryStrategies = RetryStrategies;
 
  ['get', 'head', 'post', 'put', 'patch', 'delete'].forEach(function (verb) {
    makeHelper(factory, verb);
  });
  factory.del = factory['delete'];
 
  ['jar', 'cookie'].forEach(function (method) {
    factory[method] = factory.Request.request[method];
  });
 
  return factory;
}
 
module.exports = Factory;
 
Factory.defaults = defaults;
Factory.Request = Request;
Factory.RetryStrategies = RetryStrategies;
 
// define .get/.post/... helpers
['get', 'head', 'post', 'put', 'patch', 'delete'].forEach(function (verb) {
  makeHelper(Factory, verb);
});
Factory.del = Factory['delete'];
 
['jar', 'cookie'].forEach(function (method) {
  Factory[method] = Factory.Request.request[method];
});