-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
76 lines (68 loc) · 2.16 KB
/
index.tsx
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
75
76
type Gist = {
id: string;
url: string;
files: Record<string, GistFile>;
}
type GistFile = {
filename: string;
type: string;
language: string;
raw_url: string;
size: number;
}
async function listGists(username: string): Promise<Array<Gist>> {
const url = `https://api.github.com/users/${username}/gists`;
const response = await fetch(url);
return await response.json();
}
function error(message: string, status: number = 400): Response {
const response = new Response(message, {status});
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
return response;
}
function contentTypeFor(filename: string): string {
if (filename.endsWith('js')) {
return 'application/javascript';
}
return 'text/plain';
}
const port = process.env.PORT || 3000;
const server = Bun.serve({
port,
async fetch(request) {
const [username, gisthash, filename, ...fragments] = new URL(request.url).pathname.split('/').filter(Boolean);
if (!username) {
return error('Missing username');
}
if (!gisthash) {
return error('Missing gisthash');
}
if (fragments.length > 0) {
return error(`Too many arguments: ${fragments}`);
}
const gists = await listGists(username);
if (gists.length === 0) {
return error(`No public gists for ${username}`);
}
const gist = gists.find(({id}) => id === gisthash);
if (!gist) {
return error(`No gist with id ${gisthash}`);
}
const files = Object.values(gist.files);
const file = filename ? files.find(file => file.filename === filename) : files[0];
if (!file) {
return error(filename ? `No file named ${filename}` : `No files`);
}
const fileUrl = file['raw_url'];
const resp = await fetch(fileUrl);
const res = new Response(await resp.text(), {headers: {
"content-type": contentTypeFor(file.filename),
}});
res.headers.set('Access-Control-Allow-Origin', '*');
res.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
return res;
},
});
console.log(`Listening on localhost:${server.port}`);
export {};