From 4f84e87ed84a901a20f3e8f6a02f04a31357177c Mon Sep 17 00:00:00 2001 From: Alchrist Leo <31308706+alchristleo@users.noreply.github.com> Date: Thu, 13 Oct 2022 20:14:05 +0700 Subject: [PATCH] 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 --- index.js | 9 ++++++++- test/test.js | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 51a8178..d9d95f8 100644 --- a/index.js +++ b/index.js @@ -194,7 +194,14 @@ async function httpProxy (fastify, opts) { function handler (request, reply) { const queryParamIndex = request.raw.url.indexOf('?') let dest = request.raw.url.slice(0, queryParamIndex !== -1 ? queryParamIndex : undefined) - dest = dest.replace(this.prefix, rewritePrefix) + if (this.prefix.includes(':')) { + const requestedPathElements = request.url.split('/') + const prefixPathWithVariables = this.prefix.split('/').map((_, index) => requestedPathElements[index]).join('/') + dest = dest.replace(prefixPathWithVariables, rewritePrefix) + } else { + dest = dest.replace(this.prefix, rewritePrefix) + } + reply.from(dest || '/', replyOpts) } diff --git a/test/test.js b/test/test.js index 8a96180..bbda84c 100644 --- a/test/test.js +++ b/test/test.js @@ -424,6 +424,27 @@ async function run () { t.equal(firstProxyPrefix.body, 'this is /api2/a') }) + test('rewritePrefix with variables', async t => { + const proxyServer = Fastify() + + proxyServer.register(proxy, { + upstream: `http://localhost:${origin.server.address().port}`, + prefix: '/api/:id/static', + rewritePrefix: '/api2' + }) + + await proxyServer.listen({ port: 0 }) + + t.teardown(() => { + proxyServer.close() + }) + + const firstProxyPrefix = await got( + `http://localhost:${proxyServer.server.address().port}/api/123/static/a` + ) + t.equal(firstProxyPrefix.body, 'this is /api2/a') + }) + test('rewrite location headers', async t => { const proxyServer = Fastify()