-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.ts
40 lines (40 loc) · 1.21 KB
/
index.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
import { serve } from "std/server";
import { Redis } from "@upstash/redis";
console.log(`Function "upstash-redis-counter" up and running!`);
serve(async (_req) => {
try {
const redis = new Redis({
url: Deno.env.get("UPSTASH_REDIS_REST_URL")!,
token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!,
});
const deno_region = Deno.env.get("DENO_REGION");
if (deno_region) {
// Increment region counter
await redis.hincrby("supa-edge-counter", deno_region, 1);
} else {
// Increment localhost counter
await redis.hincrby("supa-edge-counter", "localhost", 1);
}
// Get all values
const counterHash: Record<string, number> | null = await redis.hgetall(
"supa-edge-counter"
);
const counters = Object.entries(counterHash!)
.sort(([, a], [, b]) => b - a) // sort desc
.reduce(
(r, [k, v]) => ({
total: r.total + v,
regions: { ...r.regions, [k]: v },
}),
{
total: 0,
regions: {},
}
);
return new Response(JSON.stringify({ counters }), { status: 200 });
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 200,
});
}
});