Skip to content

Commit f1e044e

Browse files
committed
feat: Add preRewrite option.
Signed-off-by: Paolo Insogna <[email protected]>
1 parent a7f17bb commit f1e044e

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,12 @@ An array that contains the types of the methods. Default: `['DELETE', 'GET', 'HE
197197

198198
An array that contains the routes to handle. Default: `['/', '/*']`.
199199

200+
### `preRewrite`
201+
202+
A function that will be executed before rewriting the URL. It receives the URL, the request parameters and the prefix and must return the new URL.
203+
204+
The function cannot return a promise.
205+
200206
### `websocket`
201207

202208
This module has _partial_ support for forwarding websockets by passing a

index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,10 @@ function isExternalUrl (url) {
8383

8484
function noop () { }
8585

86+
function noopPreRewrite (url) {
87+
return url
88+
}
89+
8690
function createContext (logger) {
8791
return { log: logger }
8892
}
@@ -519,6 +523,7 @@ async function fastifyHttpProxy (fastify, opts) {
519523
opts = validateOptions(opts)
520524

521525
const preHandler = opts.preHandler || opts.beforeHandler
526+
const preRewrite = typeof opts.preRewrite === 'function' ? opts.preRewrite : noopPreRewrite
522527
const rewritePrefix = generateRewritePrefix(fastify.prefix, opts)
523528

524529
const fromOpts = Object.assign({}, opts)
@@ -585,6 +590,8 @@ async function fastifyHttpProxy (fastify, opts) {
585590
}
586591

587592
function fromParameters (url, params = {}, prefix = '/') {
593+
url = preRewrite(url, params, prefix)
594+
588595
const { path, queryParams } = extractUrlComponents(url)
589596
let dest = path
590597

test/test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,6 +981,30 @@ async function run () {
981981
t.assert.strictEqual(body, 'this is a')
982982
}
983983
})
984+
985+
test('preRewrite handler', async t => {
986+
const proxyServer = Fastify()
987+
988+
proxyServer.register(proxy, {
989+
upstream: `http://localhost:${origin.server.address().port}`,
990+
prefix: '/api',
991+
rewritePrefix: '/api2/',
992+
preRewrite (url) {
993+
return url.replace('abc', 'a')
994+
}
995+
})
996+
997+
await proxyServer.listen({ port: 0 })
998+
999+
t.after(() => {
1000+
proxyServer.close()
1001+
})
1002+
1003+
const firstProxyPrefix = await got(
1004+
`http://localhost:${proxyServer.server.address().port}/api/abc`
1005+
)
1006+
t.assert.strictEqual(firstProxyPrefix.body, 'this is /api2/a')
1007+
})
9841008
}
9851009

9861010
run()

0 commit comments

Comments
 (0)