agent.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. const CookieJar = require('cookiejar').CookieJar;
  6. const CookieAccess = require('cookiejar').CookieAccessInfo;
  7. const parse = require('url').parse;
  8. const request = require('../..');
  9. const AgentBase = require('../agent-base');
  10. let methods = require('methods');
  11. /**
  12. * Expose `Agent`.
  13. */
  14. module.exports = Agent;
  15. /**
  16. * Initialize a new `Agent`.
  17. *
  18. * @api public
  19. */
  20. function Agent(options) {
  21. if (!(this instanceof Agent)) {
  22. return new Agent(options);
  23. }
  24. AgentBase.call(this);
  25. this.jar = new CookieJar();
  26. if (options) {
  27. if (options.ca) {this.ca(options.ca);}
  28. if (options.key) {this.key(options.key);}
  29. if (options.pfx) {this.pfx(options.pfx);}
  30. if (options.cert) {this.cert(options.cert);}
  31. }
  32. }
  33. Agent.prototype = Object.create(AgentBase.prototype);
  34. /**
  35. * Save the cookies in the given `res` to
  36. * the agent's cookie jar for persistence.
  37. *
  38. * @param {Response} res
  39. * @api private
  40. */
  41. Agent.prototype._saveCookies = function(res) {
  42. const cookies = res.headers['set-cookie'];
  43. if (cookies) this.jar.setCookies(cookies);
  44. };
  45. /**
  46. * Attach cookies when available to the given `req`.
  47. *
  48. * @param {Request} req
  49. * @api private
  50. */
  51. Agent.prototype._attachCookies = function(req) {
  52. const url = parse(req.url);
  53. const access = CookieAccess(
  54. url.hostname,
  55. url.pathname,
  56. 'https:' == url.protocol
  57. );
  58. const cookies = this.jar.getCookies(access).toValueString();
  59. req.cookies = cookies;
  60. };
  61. methods.forEach(name => {
  62. const method = name.toUpperCase();
  63. Agent.prototype[name] = function(url, fn) {
  64. const req = new request.Request(method, url);
  65. req.on('response', this._saveCookies.bind(this));
  66. req.on('redirect', this._saveCookies.bind(this));
  67. req.on('redirect', this._attachCookies.bind(this, req));
  68. this._attachCookies(req);
  69. this._setDefaults(req);
  70. if (fn) {
  71. req.end(fn);
  72. }
  73. return req;
  74. };
  75. });
  76. Agent.prototype.del = Agent.prototype['delete'];