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
import { fetch } from "https://esm.town/v/std/fetch";
import { handleFetchTextResponse } from "https://esm.town/v/devdoshi/handleFetchTextResponse";
export let subscribeToPush = async (req: express.Request, res: express.Response) => {
const routes = {
POST: {
"/subscriptions": (req: express.Request, res: express.Response) => {
res.json({ yay: true });
},
},
GET: {
"/": async (req: express.Request, res: express.Response) => {
const response = await fetch(
`https://raw.githubusercontent.com/pirminrehm/service-worker-web-push-example/main/client${
req.path.substring(`/ui`.length)
}`,
).then(handleFetchTextResponse);
const contentTypeMapping = {
"html": "text/html",
"js": "application/javascript",
"css": "text/css",
};
const extensionIndex = req.path.lastIndexOf(".");
const extension = req.path.substring(extensionIndex + 1);
console.log({ extensionIndex, extension });
res.set("content-type", contentTypeMapping[extension] || "text/plain")
.send(response);
},
},
};
try {
const handler = routes[req.method][req.path];
if (handler) {
return handler(req, res);
}
const handlers = routes[req.method];
const partialMatch = Object.keys(handlers).find((k) =>
req.path.startsWith(k)
);
if (partialMatch) {
return handlers[partialMatch](req, res);
}
throw new Error("could not find a matching route handler");
}
catch (e) {
console.error(e);
return res.status(400).json({
path: req.path,
method: req.method,
error: e.message,
});
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023