Source: components/request-factory.js

  1. "use strict";
  2. var Request = require("./request");
  3. /**
  4. * Construct a factory which can create {@link Request} objects. Useful for
  5. * adding "default" handlers to requests.
  6. * @constructor
  7. */
  8. function RequestFactory() {
  9. this._resolves = [];
  10. this._rejects = [];
  11. this._timeouts = [];
  12. }
  13. /**
  14. * Generate a new request.
  15. * @param {Object=} opts The options to pass to the Request constructor, if any.
  16. * @return {Request} A new request object
  17. */
  18. RequestFactory.prototype.newRequest = function(opts) {
  19. var req = new Request(opts);
  20. req.getPromise().then((res) => {
  21. this._resolves.forEach((resolveFn) => {
  22. resolveFn(req, res);
  23. });
  24. }).catch((err) => {
  25. this._rejects.forEach((rejectFn) => {
  26. rejectFn(req, err);
  27. });
  28. });
  29. this._timeouts.forEach(function(timeoutObj) {
  30. setTimeout(function() {
  31. var promise = req.getPromise();
  32. if (!promise.isPending()) {
  33. return;
  34. }
  35. timeoutObj.fn(req);
  36. }, timeoutObj.timeout);
  37. });
  38. return req;
  39. }
  40. /**
  41. * Add a function which will be invoked for every request that is resolved.
  42. * @param {Function} fn The function to invoke. The first argument will be the
  43. * Request object, the second will be the resolve argument.
  44. */
  45. RequestFactory.prototype.addDefaultResolveCallback = function(fn) {
  46. this._resolves.push(fn);
  47. };
  48. /**
  49. * Add a function which will be invoked for every request that is rejected.
  50. * @param {Function} fn The function to invoke. The first argument will be the
  51. * Request object, the second will be the rejection argument.
  52. */
  53. RequestFactory.prototype.addDefaultRejectCallback = function(fn) {
  54. this._rejects.push(fn);
  55. };
  56. /**
  57. * Add a function which will be invoked for every request that has not been
  58. * resolved or rejected within a certain amount of time.
  59. * @param {Function} fn The function to invoke. The first argument will be the
  60. * Request object.
  61. * @param {number} durationMs The number of milliseconds to wait for a
  62. * resolution to the request.
  63. */
  64. RequestFactory.prototype.addDefaultTimeoutCallback = function(fn, durationMs) {
  65. this._timeouts.push({
  66. fn: fn,
  67. timeout: durationMs
  68. });
  69. };
  70. module.exports = RequestFactory;