forked from cloudflare/worker-template-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreceive-server.js
More file actions
71 lines (61 loc) · 1.42 KB
/
receive-server.js
File metadata and controls
71 lines (61 loc) · 1.42 KB
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
const someHTML = `
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>This is all generated using a Worker</p>
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</body>
</html>
`
const someJSON = {
result: ['some', 'results'],
errors: null,
msg: 'this is some random json',
}
/**
* rawHtmlResponse delievers a response with HTML inputted directly
* into the worker script
* @param {string} html
*/
async function rawHtmlResponse(html) {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
}
return new Response(html, init)
}
/**
* rawJsonResponse delievers a response with a Json Object inputted directly
* into the worker script
* @param {Object} json
*/
async function rawJsonResponse(json) {
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
return new Response(json, init)
}
//TODO add simple make subrequest
/**
* TODO changeto use KV will need mime types https://www.npmjs.com/package/mime-types
*/
addEventListener('fetch', event => {
const { url } = event.request
if (url.endsWith('/html')) {
return event.respondWith(rawHtmlResponse(someHTML))
}
if (url.endsWith('/json')) {
return event.respondWith(rawJsonResponse(someJSON))
}
})