Created
May 31, 2022 23:04
-
-
Save Acen/0a9be63b91b0e99533ccc28fb705081b to your computer and use it in GitHub Desktop.
Rewrite the requested URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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