Skip to content

Commit

Permalink
Merge pull request #6 from krutoo/proxy-fix-and-enhance
Browse files Browse the repository at this point in the history
Proxy middleware enhancements
  • Loading branch information
krutoo committed Apr 19, 2024
2 parents 81362b6 + 08bb79c commit eb9a9a7
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/middleware/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,25 @@ export interface ProxyRequestFilter {
}

export interface ProxyOptions {
/** Defines which requests should be proxyed. */
filter: string | string[] | ProxyRequestFilter;

/** Defines the target host. */
target: string;

/** Defines how the incoming request path should change. */
pathRewrite?: (pathname: string) => string;
}

/**
* Simple proxy middleware for servers based on Web Fetch API.
* Based on good article: https://blog.r0b.io/post/creating-a-proxy-with-deno/
*/
export function proxy({ filter, target }: ProxyOptions): Middleware {
export function proxy({ filter, target, pathRewrite = p => p }: ProxyOptions): Middleware {
const matches = createMatches(filter);

const createRequest = (url: URL, request: Request) => {
const targetURL = new URL(`.${url.pathname}`, target);
const targetURL = new URL(`.${pathRewrite(url.pathname)}`, target);
targetURL.search = url.search;

const headers = new Headers(request.headers);
Expand All @@ -38,12 +44,7 @@ export function proxy({ filter, target }: ProxyOptions): Middleware {
return next(request);
}

console.log('go proxy!');

return fetch(createRequest(url, request)).then(res => {
console.log({ ...res.headers });
return res;
});
return fetch(createRequest(url, request));
};
}

Expand Down

0 comments on commit eb9a9a7

Please sign in to comment.