Skip to content

Commit f7162fb

Browse files
ifavoMario Micklisch
and
Mario Micklisch
authoredAug 17, 2022
Add ability to handle variables in prefixed paths (#266)
Co-authored-by: Mario Micklisch <[email protected]>
1 parent b6db35c commit f7162fb

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
@@ -235,7 +235,14 @@ async function httpProxy (fastify, opts) {
235235
function handler (request, reply) {
236236
const queryParamIndex = request.raw.url.indexOf('?')
237237
let dest = request.raw.url.slice(0, queryParamIndex !== -1 ? queryParamIndex : undefined)
238-
dest = dest.replace(this.prefix, rewritePrefix)
238+
239+
if (this.prefix.includes(':')) {
240+
const requestedPathElements = request.url.split('/')
241+
const prefixPathWithVariables = this.prefix.split('/').map((_, index) => requestedPathElements[index]).join('/')
242+
dest = dest.replace(prefixPathWithVariables, rewritePrefix)
243+
} else {
244+
dest = dest.replace(this.prefix, rewritePrefix)
245+
}
239246
reply.from(dest || '/', replyOpts)
240247
}
241248

‎test/test.js

+21
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,27 @@ async function run () {
444444
t.equal(firstProxyPrefix.body, 'this is /api2/a')
445445
})
446446

447+
test('rewritePrefix with variables', async t => {
448+
const proxyServer = Fastify()
449+
450+
proxyServer.register(proxy, {
451+
upstream: `http://localhost:${origin.server.address().port}`,
452+
prefix: '/api/:id/static',
453+
rewritePrefix: '/api2'
454+
})
455+
456+
await proxyServer.listen({ port: 0 })
457+
458+
t.teardown(() => {
459+
proxyServer.close()
460+
})
461+
462+
const firstProxyPrefix = await got(
463+
`http://localhost:${proxyServer.server.address().port}/api/123/static/a`
464+
)
465+
t.equal(firstProxyPrefix.body, 'this is /api2/a')
466+
})
467+
447468
test('rewrite location headers', async t => {
448469
const proxyServer = Fastify()
449470

0 commit comments

Comments
 (0)
Please sign in to comment.