forked from forwardemail/superagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.js
More file actions
108 lines (87 loc) · 2.17 KB
/
agent.js
File metadata and controls
108 lines (87 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* Module dependencies.
*/
// eslint-disable-next-line node/no-deprecated-api
const { parse } = require('url');
const { CookieJar } = require('cookiejar');
const { CookieAccessInfo } = require('cookiejar');
const methods = require('methods');
const request = require('../..');
const AgentBase = require('../agent-base');
/**
* Expose `Agent`.
*/
module.exports = Agent;
/**
* Initialize a new `Agent`.
*
* @api public
*/
function Agent(options) {
if (!(this instanceof Agent)) {
return new Agent(options);
}
AgentBase.call(this);
this.jar = new CookieJar();
if (options) {
if (options.ca) {
this.ca(options.ca);
}
if (options.key) {
this.key(options.key);
}
if (options.pfx) {
this.pfx(options.pfx);
}
if (options.cert) {
this.cert(options.cert);
}
if (options.rejectUnauthorized === false) {
this.disableTLSCerts();
}
}
}
Agent.prototype = Object.create(AgentBase.prototype);
/**
* Save the cookies in the given `res` to
* the agent's cookie jar for persistence.
*
* @param {Response} res
* @api private
*/
Agent.prototype._saveCookies = function (res) {
const cookies = res.headers['set-cookie'];
if (cookies) this.jar.setCookies(cookies);
};
/**
* Attach cookies when available to the given `req`.
*
* @param {Request} req
* @api private
*/
Agent.prototype._attachCookies = function (request_) {
const url = parse(request_.url);
const access = new CookieAccessInfo(
url.hostname,
url.pathname,
url.protocol === 'https:'
);
const cookies = this.jar.getCookies(access).toValueString();
request_.cookies = cookies;
};
for (const name of methods) {
const method = name.toUpperCase();
Agent.prototype[name] = function (url, fn) {
const request_ = new request.Request(method, url);
request_.on('response', this._saveCookies.bind(this));
request_.on('redirect', this._saveCookies.bind(this));
request_.on('redirect', this._attachCookies.bind(this, request_));
this._setDefaults(request_);
this._attachCookies(request_);
if (fn) {
request_.end(fn);
}
return request_;
};
}
Agent.prototype.del = Agent.prototype.delete;