-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathcloudflare-kv-http.ts
232 lines (210 loc) · 6.22 KB
/
cloudflare-kv-http.ts
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { $fetch } from "ofetch";
import {
createError,
createRequiredError,
defineDriver,
joinKeys,
} from "./utils";
interface KVAuthAPIToken {
/**
* API Token generated from the [User Profile 'API Tokens' page](https://dash.cloudflare.com/profile/api-tokens)
* of the Cloudflare console.
* @see https://api.cloudflare.com/#getting-started-requests
*/
apiToken: string;
}
interface KVAuthServiceKey {
/**
* A special Cloudflare API key good for a restricted set of endpoints.
* Always begins with "v1.0-", may vary in length.
* May be used to authenticate in place of `apiToken` or `apiKey` and `email`.
* @see https://api.cloudflare.com/#getting-started-requests
*/
userServiceKey: string;
}
interface KVAuthEmailKey {
/**
* Email address associated with your account.
* Should be used along with `apiKey` to authenticate in place of `apiToken`.
*/
email: string;
/**
* API key generated on the "My Account" page of the Cloudflare console.
* Should be used along with `email` to authenticate in place of `apiToken`.
* @see https://api.cloudflare.com/#getting-started-requests
*/
apiKey: string;
}
export type KVHTTPOptions = {
/**
* Cloudflare account ID (required)
*/
accountId: string;
/**
* The ID of the KV namespace to target (required)
*/
namespaceId: string;
/**
* The URL of the Cloudflare API.
* @default https://api.cloudflare.com
*/
apiURL?: string;
/**
* Adds prefix to all stored keys
*/
base?: string;
/**
* The minimum time-to-live (ttl) for setItem in seconds.
* The default is 60 seconds as per Cloudflare's [documentation](https://developers.cloudflare.com/kv/api/write-key-value-pairs/).
*/
minTTL?: number;
} & (KVAuthServiceKey | KVAuthAPIToken | KVAuthEmailKey);
type CloudflareAuthorizationHeaders =
| {
"X-Auth-Email": string;
"X-Auth-Key": string;
"X-Auth-User-Service-Key"?: string;
Authorization?: `Bearer ${string}`;
}
| {
"X-Auth-Email"?: string;
"X-Auth-Key"?: string;
"X-Auth-User-Service-Key": string;
Authorization?: `Bearer ${string}`;
}
| {
"X-Auth-Email"?: string;
"X-Auth-Key"?: string;
"X-Auth-User-Service-Key"?: string;
Authorization: `Bearer ${string}`;
};
const DRIVER_NAME = "cloudflare-kv-http";
export default defineDriver<KVHTTPOptions>((opts) => {
if (!opts.accountId) {
throw createRequiredError(DRIVER_NAME, "accountId");
}
if (!opts.namespaceId) {
throw createRequiredError(DRIVER_NAME, "namespaceId");
}
let headers: CloudflareAuthorizationHeaders;
if ("apiToken" in opts) {
headers = { Authorization: `Bearer ${opts.apiToken}` };
} else if ("userServiceKey" in opts) {
headers = { "X-Auth-User-Service-Key": opts.userServiceKey };
} else if (opts.email && opts.apiKey) {
headers = { "X-Auth-Email": opts.email, "X-Auth-Key": opts.apiKey };
} else {
throw createError(
DRIVER_NAME,
"One of the `apiToken`, `userServiceKey`, or a combination of `email` and `apiKey` is required."
);
}
const apiURL = opts.apiURL || "https://api.cloudflare.com";
const baseURL = `${apiURL}/client/v4/accounts/${opts.accountId}/storage/kv/namespaces/${opts.namespaceId}`;
const kvFetch = $fetch.create({ baseURL, headers });
const r = (key: string = "") => (opts.base ? joinKeys(opts.base, key) : key);
const hasItem = async (key: string) => {
try {
const res = await kvFetch(`/metadata/${r(key)}`);
return res?.success === true;
} catch (err: any) {
if (!err?.response) {
throw err;
}
if (err?.response?.status === 404) {
return false;
}
throw err;
}
};
const getItem = async (key: string) => {
try {
// Cloudflare API returns with `content-type: application/octet-stream`
return await kvFetch(`/values/${r(key)}`).then((r) => r.text());
} catch (err: any) {
if (!err?.response) {
throw err;
}
if (err?.response?.status === 404) {
return null;
}
throw err;
}
};
const setItem = async (key: string, value: any, topts: any) => {
return await kvFetch(`/values/${r(key)}`, {
method: "PUT",
body: value,
query: topts?.ttl
? { expiration_ttl: Math.max(topts?.ttl, opts.minTTL || 60) }
: undefined,
});
};
const removeItem = async (key: string) => {
return await kvFetch(`/values/${r(key)}`, { method: "DELETE" });
};
const getKeys = async (base?: string) => {
const keys: string[] = [];
const params: Record<string, string | undefined> = {};
if (base || opts.base) {
params.prefix = r(base);
}
const firstPage = await kvFetch("/keys", { params });
for (const item of firstPage.result as { name: string }[]) {
keys.push(item.name);
}
const cursor = firstPage.result_info.cursor;
if (cursor) {
params.cursor = cursor;
}
while (params.cursor) {
const pageResult = await kvFetch("/keys", { params });
for (const item of pageResult.result as { name: string }[]) {
keys.push(item.name);
}
const pageCursor = pageResult.result_info.cursor;
params.cursor = pageCursor ? pageCursor : undefined;
}
return keys;
};
const clear = async () => {
const keys: string[] = await getKeys();
// Split into chunks of 10000, as the API only allows for 10,000 keys at a time
// TODO: Avoid reduce
// eslint-disable-next-line unicorn/no-array-reduce
const chunks = keys.reduce<string[][]>(
(acc, key, i) => {
if (i % 10_000 === 0) {
acc.push([]);
}
acc[acc.length - 1]!.push(key);
return acc;
},
[[]]
);
// Call bulk delete endpoint with each chunk
await Promise.all(
chunks.map((chunk) => {
if (chunk.length > 0) {
return kvFetch("/bulk/delete", {
method: "POST",
body: chunk,
});
}
})
);
};
return {
name: DRIVER_NAME,
options: opts,
hasItem,
getItem,
setItem,
removeItem,
getKeys: (base?: string) =>
getKeys(base).then((keys) =>
keys.map((key) => (opts.base ? key.slice(opts.base.length) : key))
),
clear,
};
});