-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcloudflare.js
More file actions
86 lines (72 loc) · 1.89 KB
/
cloudflare.js
File metadata and controls
86 lines (72 loc) · 1.89 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
import * as core from '@actions/core'
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()
}
}
const response = await fetch(url, {
method: 'PUT',
body: value,
headers
})
if (!response.ok) {
const body = await response.text().catch(() => '')
throw new Error(
`PUT failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`
)
}
return null
}
async function get(kvUrl, headers) {
const response = await fetch(kvUrl, { headers })
if (!response.ok) {
const body = await response.text().catch(() => '')
throw new Error(
`GET failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`
)
}
const text = await response.text()
try {
return JSON.parse(text)
} catch {
return text
}
}
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, expiration, expirationTtl)
} else {
core.info(`Getting value for ${key}`)
return get(kvUrl, headers)
}
}