This repository has been archived by the owner on Jun 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
63 lines (52 loc) · 1.5 KB
/
index.js
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
import template from "./template.js";
const jsc8 = require("jsc8")
const defaultData = { todos: [] }
const client = new jsc8({
url: "https://play.macrometa.io",
apiKey: API_KEY,
agent: fetch,
})
const insertKVPairs = (key, data) => {
const raw = { _key: key, value: data }
return client.insertKVPairs(COLLECTION_NAME, raw)
}
const getValue = (key) => {
return client.getValueForKey(COLLECTION_NAME, key)
}
const getTodos = async (request) => {
let data
let myKey
try {
const ip = request.headers.get("CF-Connecting-IP")
myKey = `data-${ip}`
const parsed = await getValue(myKey)
data = parsed.value
} catch (e) {
await insertKVPairs(myKey, defaultData)
data = defaultData
}
const body = template(JSON.stringify(data.todos || []))
return new Response(body, {
headers: { "Content-Type": "text/html" },
})
}
const updateTodos = async (request) => {
const body = await request.text()
const ip = request.headers.get("CF-Connecting-IP")
const myKey = `data-${ip}`
try {
await insertKVPairs(myKey, JSON.parse(body))
return new Response(body, { status: 200 })
} catch (err) {
return new Response(err, { status: 500 })
}
}
const handleRequest = async (request) => {
if (request.method === "PUT") {
return updateTodos(request)
}
return getTodos(request)
}
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request))
})