Skip to content

Instantly share code, notes, and snippets.

@Acen
Created May 31, 2022 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Acen/0a9be63b91b0e99533ccc28fb705081b to your computer and use it in GitHub Desktop.
Save Acen/0a9be63b91b0e99533ccc28fb705081b to your computer and use it in GitHub Desktop.
Rewrite the requested URL
addEventListener('fetch', function (event) {
event.respondWith(handleRequest(event.request));
});
const pageType = (path: string): string|false => {
switch(path)
{
case 'method':
return 'pages';
case 'book-a-consultation':
return 'pages';
case 'contact-us':
return 'pages';
case 'case-study':
return 'blogs';
case 'news':
return 'blogs';
default:
return false;
}
}
export async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname;
const chunks = path.split('/');
const lastChunk = chunks.slice(-1) as unknown as string;
const p = pageType(lastChunk.toString());
if(p){
console.log('cb', JSON.stringify(chunks));
chunks.splice(-2, 1, p)
url.pathname = '/' + chunks.join('/');
url.host = 'example.org';
return fetch(new Request(url.toString(), new Request(request)));
}else{
url.host = 'example.org';
return fetch(new Request(url.toString(), new Request(request)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment