httpclient.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter;
  3. var util = require('util');
  4. var utility = require('utility');
  5. var urllib = require('./urllib');
  6. module.exports = HttpClient;
  7. function HttpClient(options) {
  8. EventEmitter.call(this);
  9. options = options || {};
  10. if (options.agent !== undefined) {
  11. this.agent = options.agent;
  12. this.hasCustomAgent = true;
  13. } else {
  14. this.agent = urllib.agent;
  15. this.hasCustomAgent = false;
  16. }
  17. if (options.httpsAgent !== undefined) {
  18. this.httpsAgent = options.httpsAgent;
  19. this.hasCustomHttpsAgent = true;
  20. } else {
  21. this.httpsAgent = urllib.httpsAgent;
  22. this.hasCustomHttpsAgent = false;
  23. }
  24. this.defaultArgs = options.defaultArgs;
  25. }
  26. util.inherits(HttpClient, EventEmitter);
  27. HttpClient.prototype.request = HttpClient.prototype.curl = function (url, args, callback) {
  28. if (typeof args === 'function') {
  29. callback = args;
  30. args = null;
  31. }
  32. args = args || {};
  33. if (this.defaultArgs) {
  34. args = utility.assign({}, [ this.defaultArgs, args ]);
  35. }
  36. args.emitter = this;
  37. args.agent = getAgent(args.agent, this.agent);
  38. args.httpsAgent = getAgent(args.httpsAgent, this.httpsAgent);
  39. return urllib.request(url, args, callback);
  40. };
  41. HttpClient.prototype.requestThunk = function (url, args) {
  42. args = args || {};
  43. if (this.defaultArgs) {
  44. args = utility.assign({}, [ this.defaultArgs, args ]);
  45. }
  46. args.emitter = this;
  47. args.agent = getAgent(args.agent, this.agent);
  48. args.httpsAgent = getAgent(args.httpsAgent, this.httpsAgent);
  49. return urllib.requestThunk(url, args);
  50. };
  51. function getAgent(agent, defaultAgent) {
  52. return agent === undefined ? defaultAgent : agent;
  53. }