Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -605,29 +605,31 @@ async function fastifyHttpProxy (fastify, opts) {
}

dest = dest.replace(prefixPathWithVariables, rewritePrefixWithVariables)
if (queryParams) {
dest += `?${qs.stringify(queryParams)}`
}
} else {
dest = dest.replace(prefix, rewritePrefix)
}

if (queryParams) {
dest += `?${qs.stringify(queryParams)}`
}

return { url: dest || '/', options: replyOpts }
}

function handler (request, reply) {
const { url, options } = fromParameters(request.url, request.params, this.prefix)
const dest = url.split('?', 1)[0]

if (request.raw[kWs]) {
reply.hijack()
try {
wsProxy.handleUpgrade(request, url, noop)
wsProxy.handleUpgrade(request, dest, noop)
} /* c8 ignore start */ catch (err) {
request.log.warn({ err }, 'websocket proxy error')
} /* c8 ignore stop */
return
}
reply.from(url, options)
reply.from(dest, options)
}

fastify.decorateReply('fromParameters', fromParameters)
Expand Down
25 changes: 25 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ async function run () {
return 'this is /api2/a'
})

origin.get('/api2/echo-query', async (request) => {
return `query: ${JSON.stringify(request.query)}`
})

origin.get('/variable-api/:id/endpoint', async (request) => {
return `this is "variable-api" endpoint with id ${request.params.id}`
})
Expand Down Expand Up @@ -900,6 +904,27 @@ async function run () {
}
})

test('fromParameters should preserve query params with non-parameterized prefix', async t => {
let fromParametersUrl
const server = Fastify()
server.register(proxy, {
upstream: `http://localhost:${origin.server.address().port}`,
prefix: '/api',
rewritePrefix: '/api2',
preHandler (request, reply, done) {
const { url } = reply.fromParameters(request.url, request.params, '/api')
fromParametersUrl = url
done()
}
})

await server.listen({ port: 0 })
t.after(() => server.close())

await fetch(`http://localhost:${server.server.address().port}/api/echo-query?foo=bar&baz=qux`)
t.assert.strictEqual(fromParametersUrl, '/api2/echo-query?foo=bar&baz=qux')
})

test('preRewrite handler', async t => {
const proxyServer = Fastify()

Expand Down
Loading