diff --git a/README.md b/README.md index 154a61d..efbb8d0 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,18 @@ A function that will be executed before rewriting the URL. It receives the URL, The function cannot return a promise. +```javascript +// `/api/abc` will be proxied to `http://api-upstream.com/api2/xyz` +fastify.register(proxy, { + upstream: `http://api-upstream.com`, + prefix: '/api', + rewritePrefix: '/api2/', + preRewrite (url, params, prefix) { + return url.replace('abc', 'xyz'); + } +}) +``` + ### `websocket` This module has _partial_ support for forwarding websockets by passing a diff --git a/types/index.d.ts b/types/index.d.ts index 992a00e..7763d5c 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -77,6 +77,12 @@ type FastifyHttpProxy = FastifyPluginCallback< > declare namespace fastifyHttpProxy { + type ProxyPreRewriteHookHandler = ( + url: string, + params: unknown, + prefix: string + ) => string + type QueryStringFunction = ( search: string | undefined, reqUrl: string, @@ -91,6 +97,7 @@ declare namespace fastifyHttpProxy { preHandler?: ProxyPreHandlerHookHandler; beforeHandler?: ProxyPreHandlerHookHandler; preValidation?: ProxyPreValidationHookHandler; + preRewrite?: ProxyPreRewriteHookHandler; config?: Object; replyOptions?: FastifyReplyFromHooks; wsClientOptions?: ClientOptions & { queryString?: { [key: string]: unknown } | QueryStringFunction; }; diff --git a/types/index.test-d.ts b/types/index.test-d.ts index 3b044cd..0e335d9 100644 --- a/types/index.test-d.ts +++ b/types/index.test-d.ts @@ -41,6 +41,12 @@ app.register(fastifyHttpProxy, { expectType(result.options) expectType(result.url) }, + preRewrite: (url, params, prefix): string => { + expectType(url) + expectType(params) + expectType(prefix) + return '' + }, base: 'whatever', cacheURLs: 10, undici: {