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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
import { serve } from "https://deno.land/std/http/server.ts";
import "https://deno.land/x/dotenv/load.ts";
const SERVER_PORT = Deno.env.get("SERVER_PORT") ?? "8080";
const SERVER_HOST = Deno.env.get("SERVER_HOST") ?? "localhost";
const API_URL = Deno.env.get("API_URL") ?? "https://git.sr.ht/query";
const API_KEY = Deno.env.get("API_KEY");
interface QueryResponse {
data: {
repositories: {
results: Repository[];
};
};
}
interface Repository {
id: string,
name: string,
description: string,
updated: string,
visibility: "PUBLIC" | "UNLISTED" | "PRIVATE"
}
window.onload = function() {
if(!API_KEY) {
throw new Error("API_KEY is empty");
}
}
const cache = {
added: 0,
value: {} as QueryResponse,
set(data: QueryResponse) {
cache.value = data;
cache.added = +new Date();
}
}
async function getRepositories(): Promise<Repository[] | undefined> {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Authorization": "Bearer " + API_KEY,
"Content-Type": "application/json"
},
body: JSON.stringify({
query: `
{
repositories {
results {
id,
name,
description,
updated,
visibility
}
}
}
`
})
})
if (response.ok) {
let json
if (cache.added < (+new Date() - 3.6E6)) { // cached for 1 hour
json = await response.json() as QueryResponse;
cache.set(json);
console.log("from api");
} else {
json = cache.value;
console.log("from cache");
}
return json?.data.repositories.results?.filter(repo => repo.visibility === "PUBLIC") ?? [];
} else {
throw response;
}
}
console.log("srht-git-feed is running on: http://" + SERVER_HOST + ":" + SERVER_PORT);
for await (const req of serve({ port: parseInt(SERVER_PORT), hostname: SERVER_HOST })) {
try {
if (req.url === "/version.txt") {
req.respond({ body: await Deno.readTextFile("version.txt") });
} else if (req.url === "/") {
const headers = new Headers();
headers.append("Cache-Control", "public,no-transform,max-age=3600");
headers.append("Content-Type", "application/json");
headers.append("Expires", new Date(Date.now() + 3600).toUTCString());
req.respond({ body: JSON.stringify(await getRepositories()), headers: headers });
} else {
req.respond({
status: 404
});
}
} catch(err) {
req.respond({ body: JSON.stringify(err) });
}
}
|