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
import { fetch } from "https://esm.town/v/std/fetch";
import { parseAuthorizationHeader } from "https://esm.town/v/pomdtr/parseAuthorizationHeader";
export async function run(req: Request) {
const url = new URL(req.url);
const [owner, filename] = url.pathname.slice(1).split("/");
const [name] = filename.split(".");
const mime = await import("npm:mime-types");
let contentType = await mime.lookup(filename);
if (!contentType) {
contentType = "application/json";
}
url.host = "api.val.town";
url.pathname = `v1/run/${owner}.${name}`;
const body = await req.text();
const headers = {};
const authorization = req.headers.get("Authorization");
if (authorization) {
const auth = parseAuthorizationHeader(
req.headers.get("Authorization"),
);
if (auth.type == "basic") {
headers["Authorization"] = `Bearer ${auth.username}`;
}
else {
headers["Authorization"] = req.headers.get("Authorization");
}
}
const resp = await fetch(url.toString(), {
method: req.method,
body: body || undefined,
headers,
});
if (resp.status != 200) {
return resp;
}
if (contentType == "application/json") {
return resp;
}
const res = await resp.json();
return new Response(typeof res == "string" ? res : JSON.stringify(res), {
headers: { "Content-Type": contentType },
});
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
October 23, 2023
Really cool! Would be great to have an example in the README about how changing the extension changes the type. E.g. you could curl the same URL but ending in txt for a plaintext page.
Good idea!