Source: components/request.js

  1. "use strict";
  2. var Promise = require("bluebird");
  3. function generateRequestId() {
  4. return (Math.random() * 1e20).toString(36);
  5. }
  6. /**
  7. * Construct a new Request.
  8. * @constructor
  9. * @param {Object} opts Options for this request.
  10. * @param {string=} opts.id Optional ID to set on this request. One will be
  11. * generated if this is not provided.
  12. * @param {*=} opts.data Optional data to associate with this request.
  13. */
  14. function Request(opts) {
  15. opts = opts || {};
  16. this.id = opts.id || generateRequestId();
  17. this.data = opts.data;
  18. this.startTs = Date.now();
  19. this.defer = new Promise.defer();
  20. }
  21. /**
  22. * Get any optional data set on this request.
  23. * @return {*} The data
  24. */
  25. Request.prototype.getData = function() {
  26. return this.data;
  27. }
  28. /**
  29. * Get this request's ID.
  30. * @return {String} The ID.
  31. */
  32. Request.prototype.getId = function() {
  33. return this.id;
  34. }
  35. /**
  36. * Get the number of elapsed milliseconds since this request was created.
  37. * @return {number} The number of milliseconds since this request was made.
  38. */
  39. Request.prototype.getDuration = function() {
  40. return Date.now() - this.startTs;
  41. };
  42. /**
  43. * Retrieve a promise for this request which will be resolved/rejected when the
  44. * respective methods are called on this Request.
  45. * @return {Promise} A promise
  46. */
  47. Request.prototype.getPromise = function() {
  48. return this.defer.promise;
  49. };
  50. /**
  51. * Resolve a request. This should be invoked for the <i>successful processing</i>
  52. * of this request. This doesn't necessarily mean that the request was sent
  53. * through, e.g. suppressing AS virtual users' messages is still a success.
  54. * @param {*} msg The thing to resolve with.
  55. */
  56. Request.prototype.resolve = function(msg) {
  57. this.defer.resolve(msg);
  58. };
  59. /**
  60. * Reject a request. This should be invoked for requests which <i>failed to be
  61. * processed correctly</i>.
  62. * @param {*} msg The thing to reject with.
  63. */
  64. Request.prototype.reject = function(msg) {
  65. this.defer.reject(msg);
  66. };
  67. /**
  68. * Resolve or reject the promise depending on the outcome of this promise.
  69. * @param {Promise} The promise whose resolution determines the outcome of this
  70. * request.
  71. */
  72. Request.prototype.outcomeFrom = function(promise) {
  73. return promise.then(
  74. (msg) => this.resolve(msg)
  75. ).catch(
  76. (msg) => this.reject(msg)
  77. );
  78. }
  79. module.exports = Request;