List a Namespace's Keys

Lists a namespace's keys.

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * List a Namespace's Keys
8
 * Lists a namespace's keys.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  namespace_identifier: string,
13
  account_identifier: string,
14
  limit: string | undefined,
15
  prefix: string | undefined,
16
  cursor: string | undefined
17
) {
18
  const url = new URL(
19
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/storage/kv/namespaces/${namespace_identifier}/keys`
20
  );
21
  for (const [k, v] of [
22
    ["limit", limit],
23
    ["prefix", prefix],
24
    ["cursor", cursor],
25
  ]) {
26
    if (v !== undefined && v !== "") {
27
      url.searchParams.append(k, v);
28
    }
29
  }
30
  const response = await fetch(url, {
31
    method: "GET",
32
    headers: {
33
      "X-AUTH-EMAIL": auth.email,
34
      "X-AUTH-KEY": auth.key,
35
      Authorization: "Bearer " + auth.token,
36
    },
37
    body: undefined,
38
  });
39
  if (!response.ok) {
40
    const text = await response.text();
41
    throw new Error(`${response.status} ${text}`);
42
  }
43
  return await response.json();
44
}
45