-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
52 lines (40 loc) · 1.8 KB
/
main.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
52
import { db } from "./db"
const server = Bun.serve({
port: Bun.env.PORT || 3000,
static: {
'/': Response.json({ message: "county here!" }),
'/api/heartbeat': Response.json({ message: "ok" }),
},
fetch(request) {
const { method } = request
const { pathname, searchParams } = new URL(request.url)
const namespace = searchParams.get('namespace')
if (!namespace) return Response.json({ message: "namespace params is required" }, { status: 400 })
const key = searchParams.get('key')
if (!key) return Response.json({ message: "key params is required" }, { status: 400 })
if (pathname.startsWith('/api/count') && method === 'GET') return get(namespace, key)
if (pathname.startsWith('/api/count/up') && method === 'POST') return up(namespace, key)
return Response.json({ message: "not found" }, { status: 404 })
}
})
console.log(`Server running at http://${server.hostname}:${server.port}`)
function get(namespace: string, key: string) {
const query = db.query('SELECT value FROM counter where namespace = :namespace and key = :key limit 1')
const counter = query.get({ namespace, key }) as { value: number }
if (!counter) return Response.json({ message: "counter not found" }, { status: 404 })
return Response.json({ count: counter.value })
}
function up(namespace: string, key: string) {
const query = db.query('SELECT value FROM counter where namespace = :namespace and key = :key limit 1')
const counter = query.get({ namespace, key })
if (counter) {
db
.query('UPDATE counter SET value = value + 1 where namespace = :namespace and key = :key')
.run({ namespace, key })
} else {
db
.query('INSERT INTO counter (namespace, key, value) VALUES (:namespace, :key, 1)')
.run({ namespace, key })
}
return Response.json({ message: 'ok' })
}