Readme

Val Town Port of adtac/Dockerfile

a whole little fullstack (sqlite, backend js, frontend js, html) app in a single val

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
export function main(data) {
const el = document.getElementById("canvas") as HTMLCanvasElement;
const ctx = el.getContext("2d");
el.width = 0.9 * window.innerWidth * window.devicePixelRatio;
el.height = 0.9 * window.innerHeight * window.devicePixelRatio;
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
const max = data.reduce((prev, [_, n]) => (n > prev ? n : prev), 0);
document.getElementById("max").innerText = max;
ctx.beginPath();
ctx.moveTo(0, el.height);
const draw = (t, n) => {
const [x, y] = [el.width * (t - data[0][0]) / 240, el.height * (1 - n / max)];
ctx.lineTo(x, y);
ctx.moveTo(x, y);
};
let last = -1;
for (const [t, n] of data) {
if (last != -1 && t > last + 1) {
draw(last + 0.1, 0);
draw(t - 0.1, 0);
}
draw(t, n);
last = t;
}
ctx.stroke();
}
export default async function(req: Request): Promise<Response> {
const { sqlite } = await import("https://esm.town/v/std/sqlite?v=4");
const { html } = await import("https://esm.town/v/stevekrouse/html");
sqlite.execute(`CREATE TABLE IF NOT EXISTS backend_in_a_file_clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
time INTEGER NOT NULL
)`);
await sqlite.execute("INSERT INTO backend_in_a_file_clicks(time) VALUES(unixepoch())");
const results = await sqlite.execute(
"SELECT time as t, COUNT(*) as n FROM backend_in_a_file_clicks WHERE t > unixepoch()-4*60*60 GROUP BY t-t%60",
);
const data = (results.rows as any as [number, number][]).map(([t, n]) => [Math.floor(t / 60), n]);
return html(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#!/usr/bin/env docker run</title>
</head>
<body style="font-family: monospace; font-size; 12px; ">
<div style="position: absolute; top: 0; left: 0; width: 100vw; height: 100vh; background-size: 5vh 5vh; background-image: linear-gradient(to right, #f0f0f0 1px, transparent 1px), linear-gradient(to bottom, #f0f0f0 1px, transparent 1px); "></div>
<span style="position: absolute; top: 1vh; left: 5vh;">Page loads over time (last 4 hours)</span>
<span id="max" style="position: absolute; top: 5vh; left: 1vh;"></span>
<span id="min" style="position: absolute; top: 95vh; left: 1vh;">0</span>
<canvas id="canvas" style="position: absolute; top: 5vh; left: 5vw; "></canvas>
<script type="module">
import { main } from "${import.meta.url}";
const data = ${JSON.stringify(data)};
main(data);
</script>
</body>
</html>`);
}
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.