Skip to content

Commit 4f84e87

Browse files
authoredOct 13, 2022
feat: handle variable in prefixed paths in v7 (#273)
* feat: handle variable in prefixed paths in v7 * feat: handle variable in prefixed paths in v7
1 parent 9837562 commit 4f84e87

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed
 

‎index.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,14 @@ async function httpProxy (fastify, opts) {
194194
function handler (request, reply) {
195195
const queryParamIndex = request.raw.url.indexOf('?')
196196
let dest = request.raw.url.slice(0, queryParamIndex !== -1 ? queryParamIndex : undefined)
197-
dest = dest.replace(this.prefix, rewritePrefix)
197+
if (this.prefix.includes(':')) {
198+
const requestedPathElements = request.url.split('/')
199+
const prefixPathWithVariables = this.prefix.split('/').map((_, index) => requestedPathElements[index]).join('/')
200+
dest = dest.replace(prefixPathWithVariables, rewritePrefix)
201+
} else {
202+
dest = dest.replace(this.prefix, rewritePrefix)
203+
}
204+
198205
reply.from(dest || '/', replyOpts)
199206
}
200207

‎test/test.js

+21
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,27 @@ async function run () {
424424
t.equal(firstProxyPrefix.body, 'this is /api2/a')
425425
})
426426

427+
test('rewritePrefix with variables', async t => {
428+
const proxyServer = Fastify()
429+
430+
proxyServer.register(proxy, {
431+
upstream: `http://localhost:${origin.server.address().port}`,
432+
prefix: '/api/:id/static',
433+
rewritePrefix: '/api2'
434+
})
435+
436+
await proxyServer.listen({ port: 0 })
437+
438+
t.teardown(() => {
439+
proxyServer.close()
440+
})
441+
442+
const firstProxyPrefix = await got(
443+
`http://localhost:${proxyServer.server.address().port}/api/123/static/a`
444+
)
445+
t.equal(firstProxyPrefix.body, 'this is /api2/a')
446+
})
447+
427448
test('rewrite location headers', async t => {
428449
const proxyServer = Fastify()
429450

0 commit comments

Comments
 (0)
Please sign in to comment.