Skip to content

Commit

Permalink
feat: handle variable in prefixed paths in v7 (#273)
Browse files Browse the repository at this point in the history
* feat: handle variable in prefixed paths in v7

* feat: handle variable in prefixed paths in v7
  • Loading branch information
alchristleo authored Oct 13, 2022
1 parent 9837562 commit 4f84e87
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
21 changes: 21 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 4f84e87

Please sign in to comment.