You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.7 KiB

  1. 'use strict';
  2. var core = require('../'),
  3. isArray = require('lodash/isArray'),
  4. isFunction = require('lodash/isFunction'),
  5. isObjectLike = require('lodash/isObjectLike');
  6. module.exports = function (options) {
  7. var errorText = 'Please verify options'; // For better minification because this string is repeating
  8. if (!isObjectLike(options)) {
  9. throw new TypeError(errorText);
  10. }
  11. if (!isFunction(options.request)) {
  12. throw new TypeError(errorText + '.request');
  13. }
  14. if (!isArray(options.expose) || options.expose.length === 0) {
  15. throw new TypeError(errorText + '.expose');
  16. }
  17. var plumbing = core({
  18. PromiseImpl: options.PromiseImpl,
  19. constructorMixin: options.constructorMixin
  20. });
  21. // Intercepting Request's init method
  22. var originalInit = options.request.Request.prototype.init;
  23. options.request.Request.prototype.init = function RP$initInterceptor(requestOptions) {
  24. // Init may be called again - currently in case of redirects
  25. if (isObjectLike(requestOptions) && !this._callback && !this._rp_promise) {
  26. plumbing.init.call(this, requestOptions);
  27. }
  28. return originalInit.apply(this, arguments);
  29. };
  30. // Exposing the Promise capabilities
  31. var thenExposed = false;
  32. for ( var i = 0; i < options.expose.length; i+=1 ) {
  33. var method = options.expose[i];
  34. plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
  35. options.request.Request.prototype,
  36. null,
  37. '_rp_promise',
  38. method
  39. );
  40. if (method === 'then') {
  41. thenExposed = true;
  42. }
  43. }
  44. if (!thenExposed) {
  45. throw new Error('Please expose "then"');
  46. }
  47. };