-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnormalize-request.ts
52 lines (44 loc) · 1.53 KB
/
normalize-request.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Config } from '../config';
const MEDIA_FILE_EXTENSIONS = new Set([
'css',
'csv',
'gif',
'ico',
'jpeg',
'jpg',
'js',
'json',
'otf',
'png',
'svg',
'ttf',
'webp',
'woff',
'woff2',
]);
const hasMediaFileExtension = (path: string): boolean => MEDIA_FILE_EXTENSIONS.has(path.split('.').pop()?.toLowerCase() || '');
export default function normalizeRequest(request: Request, routes: Config['routes']): { request: Request, cache: boolean } {
const url = new URL(request.url);
const originalUrlWithoutScheme = url.hostname + url.pathname;
const path = originalUrlWithoutScheme.replace(/^.*?\//gi, '');
for (const [route, replacement] of Object.entries(routes)) {
if (request.url.includes(route) && (originalUrlWithoutScheme.startsWith(route) || route.startsWith('/'))) {
let newUrl = replacement;
const singlePageApp = newUrl.startsWith('s3://');
const isMediaFile = hasMediaFileExtension(request.url)
if (singlePageApp) {
newUrl = newUrl.replace(new RegExp('s3://([^.]+).([^/]+)(/?)(.*)'), 'https://s3.$1.amazonaws.com/$2$3$4')
}
let updatedUrl = originalUrlWithoutScheme.replace(route, newUrl)
if (singlePageApp && !isMediaFile) {
updatedUrl = newUrl + '/index.html'
}
updatedUrl += newUrl.endsWith('/') ? updatedUrl + path : ''
if (!updatedUrl.startsWith('https://')) {
updatedUrl = 'https://' + updatedUrl
}
return { request: new Request(updatedUrl), cache: true };
}
}
return { request, cache: false };
}