-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathindex.js
65 lines (58 loc) · 1.74 KB
/
index.js
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
/**
* Builds a reply to the given request
*/
const reply = async (request) => {
if (request.method != "GET") {
// Don't allow other methods.
// Here you can see how to return a custom status
return new Response("Method not allowed", {
status: 405
});
}
// Body response
let body;
try {
let res = await fetch('https://jsonplaceholder.typicode.com/posts/');
let json = await res.json();
// Build a new response.
// Add some basic sanitization
body = `<!DOCTYPE html>
<head>
<title>Wasm Workers Server</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
<style>
body { max-width: 1000px; }
main { margin: 5rem 0; }
h1, p { text-align: center; }
h1 { margin-bottom: 2rem; }
pre { font-size: .9rem; }
pre > code { padding: 2rem; }
p { margin-top: 2rem; }
</style>
</head>
<body>
<main>
<h1>Hello from Wasm Workers Server 👋</h1>
<p>Available articles:</p>
<ul>
${json.map(({ title }) => `<li>${title.replace("<", "<").replace(">", ">")}</li>`).join("")}
</ul>
<p>
This page was generated by a JavaScript file running in WebAssembly.
</p>
</main>
</body>`;
} catch (e) {
body = `There was an error with the request: ${e}`;
}
let response = new Response(body);
// Add a new header
response.headers.set("x-generated-by", "wasm-workers-server");
return response;
}
// Subscribe to the Fetch event
addEventListener("fetch", event => {
return event.respondWith(reply(event.request));
});