-
-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathundici-proxy-agent.test.js
101 lines (78 loc) · 2.45 KB
/
undici-proxy-agent.test.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
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
'use strict'
const { test, after } = require('node:test')
const { createServer } = require('node:http')
const Fastify = require('fastify')
const { request } = require('undici')
const { createProxy } = require('proxy')
const fastifyProxyFrom = require('..')
const { isIPv6 } = require('node:net')
const configFormat = {
string: (value) => value,
'url instance': (value) => new URL(value),
object: (value) => ({ uri: value })
}
for (const [description, format] of Object.entries(configFormat)) {
test(`use undici ProxyAgent to connect through proxy - configured via ${description}`, async (t) => {
t.plan(3)
const target = await buildServer()
const proxy = await buildProxy()
after(() => {
target.close()
proxy.close()
})
let targetAddress = target.address().address
if (isIPv6(targetAddress)) {
targetAddress = `[${targetAddress}]`
}
let proxyAddress = proxy.address().address
if (isIPv6(proxyAddress)) {
proxyAddress = `[${proxyAddress}]`
}
const targetUrl = `http://${targetAddress}:${target.address().port}`
const proxyUrl = `http://${proxyAddress}:${proxy.address().port}`
proxy.on('connect', () => {
t.assert.ok(true, 'should connect to proxy')
})
target.on('request', (_req, res) => {
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify({ hello: 'world' }))
})
const instance = Fastify()
after(() => {
instance.close()
})
instance.register(fastifyProxyFrom, {
base: targetUrl,
undici: {
proxy: format(proxyUrl)
}
})
instance.get('/', (_request, reply) => {
reply.from()
})
await instance.listen({ port: 0 })
let instanceAddress = proxy.address().address
if (isIPv6(instanceAddress)) {
if (instanceAddress === '::') {
instanceAddress = '::1'
} else {
instanceAddress = `[${instanceAddress}]`
}
}
const response = await request(`http://localhost:${instance.server.address().port}`)
t.assert.strictEqual(response.statusCode, 200)
t.assert.deepStrictEqual(await response.body.json(), { hello: 'world' })
})
}
function buildServer () {
return new Promise((resolve) => {
const server = createServer()
server.listen(0, () => resolve(server))
})
}
function buildProxy () {
return new Promise((resolve) => {
const server = createProxy(createServer())
server.listen(0, () => resolve(server))
})
}