Repository navigation
Expand file tree
/
Copy pathcloudflare.js
More file actions
136 lines (115 loc) · 3.29 KB
/
Copy pathcloudflare.js
File metadata and controls
136 lines (115 loc) · 3.29 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
}
// Cloudflare does not document the error for a missing key. The API returns
// code 10009 with the message "get: 'key not found'". Other 404s (unknown
// namespace or account) carry other errors and must not count as missing.
function isKeyNotFound(body) {
try {
return JSON.parse(body).errors.some(
(error) =>
error.code === 10009 || /key not found/i.test(error.message ?? '')
)
} catch {
return false
}
}
async function get(kvUrl, headers, failOnMissing) {
const response = await fetch(kvUrl, { headers })
if (!response.ok) {
const body = await response.text().catch(() => '')
if (response.status === 404 && !failOnMissing && isKeyNotFound(body)) {
return ''
}
throw new Error(
`GET failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`
)
}
const text = await response.text()
try {
return JSON.parse(text)
} catch {
return text
}
}
async function remove(kvUrl, headers) {
const response = await fetch(kvUrl, { method: 'DELETE', headers })
if (!response.ok) {
const body = await response.text().catch(() => '')
throw new Error(
`DELETE failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`
)
}
return null
}
const OPERATIONS = ['get', 'put', 'delete']
export default async function kv(
accountId,
accountEmail,
apiKey,
namespaceId,
key,
value,
expiration,
expirationTtl,
operation,
failOnMissing = true
) {
if (operation && !OPERATIONS.includes(operation)) {
throw new Error(
`Invalid operation: ${operation}. Use one of: ${OPERATIONS.join(', ')}`
)
}
const kvUrl = `https://api.cloudflare.com/client/${API_VERSION}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${encodeURIComponent(key)}`
const headers = accountEmail
? {
'X-Auth-Key': apiKey,
'X-Auth-Email': accountEmail
}
: {
Authorization: `Bearer ${apiKey}`
}
// Without an explicit operation, infer it: a non-empty value sets, else get.
const op =
operation ||
(value && (value.length > 0 || Object.keys(value).length > 0)
? 'put'
: 'get')
if (op === 'put') {
core.info(`Setting value for ${key}`)
return set(kvUrl, headers, value ?? '', expiration, expirationTtl)
} else if (op === 'delete') {
core.info(`Deleting ${key}`)
return remove(kvUrl, headers)
} else {
core.info(`Getting value for ${key}`)
return get(kvUrl, headers, failOnMissing)
}
}