-
Notifications
You must be signed in to change notification settings - Fork 50
/
index.js
59 lines (51 loc) · 1.44 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
const micro = require('micro')
const { resolve } = require('url')
const fetch = require('node-fetch')
const lintRules = require('./lib/lint-rules')
module.exports = (rules) => {
const lintedRules = lintRules(rules).map(({pathname, pathnameRe, method, dest}) => {
const methods = method ? method.reduce((final, c) => {
final[c.toLowerCase()] = true
return final
}, {}) : null
return {
pathname,
pathnameRegexp: new RegExp(pathnameRe || pathname || '.*'),
dest,
methods
}
})
return micro(async (req, res) => {
for (const { pathnameRegexp, methods, dest } of lintedRules) {
if (pathnameRegexp.test(req.url) && (!methods || methods[req.method.toLowerCase()])) {
await proxyRequest(req, res, dest)
return
}
}
res.writeHead(404)
res.end('404 - Not Found')
})
}
async function proxyRequest (req, res, dest) {
const newUrl = resolve(dest, req.url)
const proxyRes = await fetch(newUrl, {
method: req.method,
headers: req.headers,
body: req
})
// Forward headers
const headers = proxyRes.headers.raw()
for (const key of Object.keys(headers)) {
res.setHeader(key, headers[key])
}
// Stream the proxy response
proxyRes.body.pipe(res)
proxyRes.body.on('error', (err) => {
console.error(`Error on proxying url: ${newUrl}`)
console.error(err.stack)
res.end()
})
req.on('abort', () => {
proxyRes.body.destroy()
})
}