forked from fastify/fastify-http-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
104 lines (89 loc) · 2.58 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict'
const From = require('fastify-reply-from')
const WebSocketPlugin = require('fastify-websocket')
const WebSocket = require('ws')
const { pipeline } = require('stream')
const nonWsMethods = ['DELETE', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
module.exports = async function (fastify, opts) {
if (!opts.upstream) {
throw new Error('upstream must be specified')
}
const preHandler = opts.preHandler || opts.beforeHandler
const rewritePrefix = opts.rewritePrefix || ''
const fromOpts = Object.assign({}, opts)
fromOpts.base = opts.upstream
fromOpts.prefix = undefined
const oldRewriteHeaders = (opts.replyOptions || {}).rewriteHeaders
const replyOpts = Object.assign({}, opts.replyOptions, {
rewriteHeaders
})
fromOpts.rewriteHeaders = rewriteHeaders
fastify.register(From, fromOpts)
if (opts.proxyPayloads !== false) {
fastify.addContentTypeParser('application/json', bodyParser)
fastify.addContentTypeParser('*', bodyParser)
}
function rewriteHeaders (headers) {
const location = headers.location
if (location) {
headers.location = location.replace(rewritePrefix, fastify.prefix)
}
if (oldRewriteHeaders) {
headers = oldRewriteHeaders(headers)
}
return headers
}
function bodyParser (req, payload, done) {
done(null, payload)
}
if (opts.websocket) {
fastify.register(WebSocketPlugin, opts.websocket)
}
fastify.get('/', {
preHandler,
config: opts.config || {},
handler,
wsHandler
})
fastify.get('/*', {
preHandler,
config: opts.config || {},
handler,
wsHandler
})
fastify.route({
url: '/',
method: nonWsMethods,
preHandler,
config: opts.config || {},
handler
})
fastify.route({
url: '/*',
method: nonWsMethods,
preHandler,
config: opts.config || {},
handler
})
function handler (request, reply) {
var dest = request.raw.url
dest = dest.replace(this.prefix, rewritePrefix)
reply.from(dest || '/', replyOpts)
}
function wsHandler (conn, req) {
// TODO support paths and querystrings
// TODO support rewriteHeader
// TODO support rewritePrefix
const ws = new WebSocket(opts.upstream)
const stream = WebSocket.createWebSocketStream(ws)
// TODO fastify-websocket should create a logger for each connection
fastify.log.info('starting websocket tunnel')
pipeline(conn, stream, conn, function (err) {
if (err) {
fastify.log.info({ err }, 'websocket tunnel terminated with error')
return
}
fastify.log.info('websocket tunnel terminated')
})
}
}