This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
84 lines (71 loc) · 2.41 KB
/
index.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
const { isIP } = require('net')
const { format, parse } = require('url')
const resolve = require('@zeit/dns-cached-resolve').default
const { dnsCachedUrl } = require('./util')
module.exports = setup
const isRedirect = v => ((v / 100) | 0) === 3
function setup(fetch) {
if (!fetch) {
fetch = require('node-fetch')
}
const { Headers } = fetch
async function fetchCachedDns(url, opts) {
const parsed = parse(url)
const originalHost = parsed.host
const ip = isIP(parsed.hostname)
if (ip === 0) {
if (!opts) opts = {}
opts.headers = new Headers(opts.headers)
if (!opts.headers.has('Host')) {
opts.headers.set('Host', parsed.host)
}
opts.redirect = 'manual'
parsed.host = await resolve(parsed.hostname)
if (parsed.port) {
parsed.host += `:${parsed.port}`
}
url = format(parsed)
}
const res = await fetch(url, opts)
// Update `res.url` to contain the original hostname instead of the IP address
res[dnsCachedUrl] = url
Object.defineProperty(res, 'url', {
get() {
return parsed.href
}
})
if (isRedirect(res.status)) {
const redirectOpts = Object.assign({}, opts)
redirectOpts.headers = new Headers(opts.headers)
// Per fetch spec, for POST request with 301/302 response, or any
// request with 303 response, use GET when following redirect
if (
res.status === 303 ||
((res.status === 301 || res.status === 302) && opts.method === 'POST')
) {
redirectOpts.method = 'GET'
redirectOpts.body = null
redirectOpts.headers.delete('content-length')
}
// Set the proper `Host` request header, considering that node-fetch will
// absolutize a relative redirect URL, so the IP address needs to be
// replaced with the original hostname as well.
const location = res.headers.get('Location')
const parsedLocation = parse(location)
if (parsedLocation.host === parsed.host) {
parsedLocation.host = originalHost
}
redirectOpts.headers.set('Host', parsedLocation.host)
if (opts.onRedirect) {
opts.onRedirect(res, redirectOpts)
}
return fetchCachedDns(format(parsedLocation), redirectOpts)
}
return res
}
for (const key of Object.keys(fetch)) {
fetchCachedDns[key] = fetch[key]
}
fetchCachedDns.default = fetchCachedDns
return fetchCachedDns
}