-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloudflare-worker-dev.tsx
71 lines (61 loc) · 1.83 KB
/
cloudflare-worker-dev.tsx
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { getMaintenanceHtml, wrapInTemplate, Url } from './utils'
const basePath = '/___cloudflare_worker_dev'
const components = [
{
title: 'Maintenance Template (English)',
subpath: 'maintenance-en',
component: getMaintenanceHtml({ lang: 'en' }),
},
{
title: 'Maintenance Template (German)',
subpath: 'maintenance-de',
component: getMaintenanceHtml({ lang: 'de' }),
},
{
title: 'Maintenance Template (English; with end date)',
subpath: 'maintenance-en-with-end-date',
component: getMaintenanceHtml({ lang: 'en', end: new Date() }),
},
{
title: 'Maintenance Template (German; with end date)',
subpath: 'maintenance-de-with-end-date',
component: getMaintenanceHtml({ lang: 'de', end: new Date() }),
},
]
export function cloudflareWorkerDev(request: Request) {
const pathname = Url.fromRequest(request).pathnameWithoutTrailingSlash
if (!pathname.startsWith(basePath)) return null
const subpath = pathname.substring(basePath.length)
if (subpath === '' || subpath === '/') {
return createIndexHtml()
}
const componentSpec = components.find(
({ subpath: componentSubpath }) => subpath === '/' + componentSubpath,
)
return componentSpec != null
? createHtmlResponse(componentSpec.component)
: null
}
function createIndexHtml() {
const listHtml = components
.map(({ title, subpath }) => {
return `<li><a href="${basePath}/${subpath}">${title}</a></li>`
})
.join('')
return createHtmlResponse(
wrapInTemplate({
title: 'Serlo Cloudflare Worker: Preview of components',
lang: 'en',
content: `<ul>${listHtml}</ul>`,
}),
)
}
function createHtmlResponse(html: string, opt?: ResponseInit) {
return new Response(html, {
...opt,
headers: {
...opt?.headers,
'Content-Type': 'text/html;charset=utf-8',
},
})
}