-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstats.ts
51 lines (47 loc) · 1.23 KB
/
stats.ts
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
/**
* Example of collecting statistics on data not tied to a Convex table.
*/
import { mutation, query } from "./_generated/server";
import { v } from "convex/values";
import { DirectAggregate } from "@convex-dev/aggregate";
import { components } from "./_generated/api";
const stats = new DirectAggregate<{
Key: number;
Id: string;
}>(components.stats);
export const reportLatency = mutation({
args: {
latency: v.number(),
},
returns: v.null(),
handler: async (ctx, { latency }) => {
await stats.insert(ctx, {
key: latency,
id: new Date().toISOString(),
sumValue: latency,
});
},
});
export const getStats = query({
args: {},
handler: async (ctx) => {
const count = await stats.count(ctx);
if (count === 0) {
throw new Error("No data");
}
const mean = (await stats.sum(ctx)) / count;
const median = (await stats.at(ctx, Math.floor(count / 2))).key;
const p75 = (await stats.at(ctx, Math.floor(count * 0.75))).key;
const p95 = (await stats.at(ctx, Math.floor(count * 0.95))).key;
const min = (await stats.min(ctx))!.key;
const max = (await stats.max(ctx))!.key;
return {
mean,
median,
p75,
p95,
max,
min,
};
},
});