-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.mjs
71 lines (61 loc) · 1.45 KB
/
index.mjs
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
64
65
66
67
68
69
70
71
import got from "got";
export default class CloudflareKV {
constructor({ accountId, apiToken, namespaceId } = {}) {
this.accountId = accountId || process.env.CLOUDFLARE_ACCOUNT_ID;
this.apiToken = apiToken || process.env.CLOUDFLARE_API_TOKEN;
this.namespaceId = namespaceId || process.env.CLOUDFLARE_NAMESPACE_ID;
}
/**
* @returns {Record<string, string>}
*/
getHeaders() {
return {
Authorization: `Bearer ${this.apiToken}`,
};
}
/**
* @param {string} key
* @returns {string}
*/
getUrl(key) {
return `https://api.cloudflare.com/client/v4/accounts/${this.accountId}/storage/kv/namespaces/${this.namespaceId}/values/${key}`;
}
/**
* @param {string} key
* @returns {Promise<void>}
*/
async delete(key) {
const url = this.getUrl(key);
const headers = this.getHeaders();
await got.delete(url, {
headers,
});
}
/**
* @template T
* @param {string} key
* @returns {Promise<T>}
*/
async get(key) {
const url = this.getUrl(key);
const headers = this.getHeaders();
const response = await got.get(url, {
headers,
responseType: "json",
});
return response.body;
}
/**
* @param {string} key
* @param {Record<string, any>} value
* @returns {Promise<void>}
*/
async put(key, value) {
const url = this.getUrl(key);
const headers = this.getHeaders();
await got.put(url, {
headers,
json: value,
});
}
}