-
Notifications
You must be signed in to change notification settings - Fork 500
/
proxy-agent.js
59 lines (48 loc) · 1.16 KB
/
proxy-agent.js
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
'use strict'
const { kClients, kProxy } = require('./core/symbols')
const url = require('url')
const Agent = require('./agent')
const Dispatcher = require('./dispatcher')
const { InvalidArgumentError } = require('./core/errors')
const kAgent = Symbol('proxy agent')
class ProxyAgent extends Dispatcher {
constructor (opts) {
super(opts)
this[kProxy] = buildProxyOptions(opts)
const agent = new Agent(opts)
this[kAgent] = agent
this[kClients] = agent[kClients]
}
dispatch (opts, handler) {
const { host } = url.parse(opts.origin)
return this[kAgent].dispatch(
{
...opts,
origin: this[kProxy].uri,
path: opts.origin + opts.path,
headers: {
...opts.headers,
host
}
},
handler
)
}
async close () {
await this[kAgent].close()
this[kClients].clear()
}
}
function buildProxyOptions (opts) {
if (typeof opts === 'string') {
opts = { uri: opts }
}
if (!opts || !opts.uri) {
throw new InvalidArgumentError('Proxy opts.uri is mandatory')
}
return {
uri: opts.uri,
protocol: opts.protocol || 'https'
}
}
module.exports = ProxyAgent