maxm-valtownanalytics.web.val.run
Readme

Val Town Analytics

WIP!

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
/** @jsxImportSource https://esm.sh/react */
import { DateTime } from "https://cdn.skypack.dev/luxon@2.3.2";
import { extractValInfo } from "https://esm.town/v/pomdtr/extractValInfo?v=27";
import { sqlite } from "https://esm.town/v/std/sqlite?v=6";
import { renderToString } from "npm:react-dom/server";
const { author, name, httpEndpoint } = extractValInfo(import.meta.url);
sqlite.batch([
{
sql: `CREATE TABLE IF NOT EXISTS ${name}_impressions (
id INTEGER PRIMARY KEY,
timestamp TEXT NOT NULL DEFAULT (datetime('now')),
val TEXT NOT NULL,
event_name TEXT,
url TEXT,
meta TEXT
);`,
args: [],
},
]);
const getRunningValInfo = () => {
const urlOfRunningVal = (new Error()).stack.split("\n").at(-1).split(" ").at(-1).split(":").slice(0, 2).join(":");
return extractValInfo(urlOfRunningVal);
};
export const initAnalytics = () => {
try {
const runningValInfo = getRunningValInfo();
if (runningValInfo.author == author && runningValInfo.name == name) {
// If we happen to have imported ourself, don't report import analytics. Would loop.
return;
}
// Do not await the response
fetch(`${httpEndpoint}/event?name=import-init&val=${runningValInfo.author}/${runningValInfo.name}`);
} catch (e) {
console.error(`Error initializing analytics: ${e}`);
}
};
export const analyticsHandlerWrapper = (
handler: (req: Request) => Response | Promise<Response>,
): (req: Request) => Response | Promise<Response> => {
const runningValInfo = getRunningValInfo();
return async (req: Request): Promise<Response> => {
fetch(`${httpEndpoint}/event?name=request&val=${runningValInfo.author}/${runningValInfo.name}&url=${req.url}`);
return handler(req);
};
};
const valCounts = async (): Promise<{ count: number; val: string }[]> => {
const result = await sqlite.execute(
`select val, count(*) as count from ${name}_impressions group by val order by count desc limit 100`,
);
return (result.rows as [string, number][]).map((row) => ({ count: row[1], val: row[0] }));
};
const queryForImpressions = async (
val: string,
start: string,
end: string,
intervalMinutes: number,
timeZone: string,
) => {
const startDate = DateTime.fromISO(start, { zone: "utc" }).setZone(timeZone);
const endDate = DateTime.fromISO(end, { zone: "utc" }).setZone(timeZone);
const startString = startDate.toFormat("yyyy-MM-dd HH:mm:ss");
const endString = endDate.toFormat("yyyy-MM-dd HH:mm:ss");
return await sqlite.execute({
sql: `
WITH params AS (
SELECT
? AS interval_minutes,
? AS start_time,
? AS end_time
)
SELECT
strftime('%Y-%m-%d %H:%M:00', datetime(
(strftime('%s', timestamp) / (interval_minutes * 60)) * (interval_minutes * 60), 'unixepoch'
)) AS bucket,
COUNT(*) AS count
FROM
${name}_impressions,
params
WHERE
timestamp BETWEEN start_time AND end_time
AND val = ?
GROUP BY bucket
ORDER BY bucket`,
args: [intervalMinutes, startString, endString, val],
});
};
async function handler(req: Request): Promise<Response> {
const url = new URL(req.url);
if (req.method === "GET" && url.pathname === "/event") {
const val = url.searchParams.get("val");
const eventName = url.searchParams.get("name");
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
v153
May 30, 2024