Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/lib/cloudDBAdapter.js
1126 views
1
const got = require('got')
2
3
const stringify = obj => JSON.stringify(obj, null, 2)
4
const parse = str => JSON.parse(str, (_, v) => {
5
if (
6
v !== null &&
7
typeof v === 'object' &&
8
'type' in v &&
9
v.type === 'Buffer' &&
10
'data' in v &&
11
Array.isArray(v.data)) {
12
return Buffer.from(v.data)
13
}
14
return v
15
})
16
class CloudDBAdapter {
17
constructor(url, {
18
serialize = stringify,
19
deserialize = parse,
20
fetchOptions = {}
21
} = {}) {
22
this.url = url
23
this.serialize = serialize
24
this.deserialize = deserialize
25
this.fetchOptions = fetchOptions
26
}
27
28
async read() {
29
try {
30
let res = await got(this.url, {
31
method: 'GET',
32
headers: {
33
'Accept': 'application/json;q=0.9,text/plain'
34
},
35
...this.fetchOptions
36
})
37
if (res.statusCode !== 200) throw res.statusMessage
38
return this.deserialize(res.body)
39
} catch (e) {
40
return null
41
}
42
}
43
44
async write(obj) {
45
let res = await got(this.url, {
46
method: 'POST',
47
headers: {
48
'Content-Type': 'application/json'
49
},
50
...this.fetchOptions,
51
body: this.serialize(obj)
52
})
53
if (res.statusCode !== 200) throw res.statusMessage
54
return res.body
55
}
56
}
57
58
module.exports = CloudDBAdapter
59
60