-
Notifications
You must be signed in to change notification settings - Fork 1
/
cloudflare.js
73 lines (62 loc) · 1.54 KB
/
cloudflare.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
64
65
66
67
68
69
70
71
72
73
import core from '@actions/core'
import fetch from 'node-fetch'
const API_VERSION = 'v4'
async function set(kvUrl, headers, value, expiration, expirationTtl) {
let url = kvUrl
headers['Content-Type'] = 'text/plain'
if (expiration) {
url = `${url}?expiration=${expiration}`
} else if (expirationTtl) {
url = `${url}?expiration_ttl=${expirationTtl}`
}
if (typeof value !== 'string') {
if (Object.keys(value).length > 0) {
value = JSON.stringify(value)
} else {
value = value.toString()
}
}
await fetch(url, {
method: 'PUT',
body: value,
headers
})
return null
}
async function get(kvUrl, headers) {
const response = await fetch(kvUrl, {
headers,
responseType: 'json',
responseEncoding: 'utf8'
})
const data = await response.text()
const json = JSON.parse(data)
return json
}
export default async function kv(
accountId,
accountEmail,
apiKey,
namespaceId,
key,
value,
expiration,
expirationTtl
) {
const kvUrl = `https://api.cloudflare.com/client/${API_VERSION}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`
const headers = accountEmail
? {
'X-Auth-Key': apiKey,
'X-Auth-Email': accountEmail
}
: {
Authorization: `Bearer ${apiKey}`
}
if (value && (value.length > 0 || Object.keys(value).length > 0)) {
core.info(`Setting value for ${key}`)
return set(kvUrl, headers, value, expirationTtl)
} else {
core.info(`Getting value for ${key}`)
return get(kvUrl, headers)
}
}