Public
HTTP (deprecated)
pomdtr-http_client.web.val.run
March 19, 2024
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
72
73
74
/** @jsxImportSource npm:preact **/
import { html } from "https://esm.town/v/stevekrouse/html?v=5";
import { Base64 } from "npm:js-base64";
import { render } from "npm:preact-render-to-string";
type SerializedRequest = {
url: string;
method: string;
headers: [string, string][];
body: string | undefined;
};
type Bookmark = {
label: string;
request: Request;
};
async function serializeRequest(request: Request): Promise<SerializedRequest> {
return {
url: request.url,
method: request.method,
headers: Array.from(request.headers.entries()),
body: request.body ? Base64.encode(await request.text()) : undefined,
};
}
const getBody = async (bookmarks: Bookmark[]) => {
const serializedBookmarks = JSON.stringify(
await Promise.all(bookmarks.map(async (bookmark) => ({
label: bookmark.label,
request: await serializeRequest(bookmark.request),
}))),
);
return render(
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>REST Client</title>
<link rel="icon" href="https://fav.farm/🌐" />
<script src="https://cdn.tailwindcss.com"></script>
<script
type="module"
src="https://cdn.jsdelivr.net/npm/code-mirror-web-component@0.0.20/dist/code-mirror.js"
>
</script>
</head>
<body class="bg-orange-100">
<div id="app" data-bookmarks={serializedBookmarks}></div>
<script type="module" src="https://esm.town/v/pomdtr/http_client_component"></script>
</body>
</html>,
);
};
export function httpClient(next: (req: Request) => Response | Promise<Response>, options: {
path: string;
bookmarks: Bookmark[];
} = { path: "/", bookmarks: [] }) {
return async (req: Request) => {
const url = new URL(req.url);
if (url.pathname == options.path) {
return html(await getBody(options.bookmarks));
}
return next(req);
};
}
export default async function(req: Request) {
const bookmarks = [{ label: "Dummy Request", request: new Request("https://dummyjson.com/products") }];
return html(await getBody(bookmarks));
}
March 19, 2024