the best lightweight web dev stack built on bun
1import { eq } from "drizzle-orm";
2import db from "../db/db";
3import { counters } from "../db/schema";
4
5export function getCounterForUser(userId: number): number {
6 const counter = db
7 .select()
8 .from(counters)
9 .where(eq(counters.user_id, userId))
10 .get();
11
12 return counter?.count ?? 0;
13}
14
15export function incrementCounter(userId: number): number {
16 // Try to update existing counter
17 const existing = db
18 .select()
19 .from(counters)
20 .where(eq(counters.user_id, userId))
21 .get();
22
23 if (existing) {
24 const newCount = existing.count + 1;
25 db.update(counters)
26 .set({ count: newCount, updated_at: new Date() })
27 .where(eq(counters.user_id, userId))
28 .run();
29 return newCount;
30 }
31
32 // Create new counter starting at 1
33 db.insert(counters).values({ user_id: userId, count: 1 }).run();
34 return 1;
35}
36
37export function decrementCounter(userId: number): number {
38 const existing = db
39 .select()
40 .from(counters)
41 .where(eq(counters.user_id, userId))
42 .get();
43
44 if (existing) {
45 const newCount = existing.count - 1;
46 db.update(counters)
47 .set({ count: newCount, updated_at: new Date() })
48 .where(eq(counters.user_id, userId))
49 .run();
50 return newCount;
51 }
52
53 // Create new counter starting at -1
54 db.insert(counters).values({ user_id: userId, count: -1 }).run();
55 return -1;
56}
57
58export function resetCounter(userId: number): void {
59 db.update(counters)
60 .set({ count: 0, updated_at: new Date() })
61 .where(eq(counters.user_id, userId))
62 .run();
63}