0
List Buckets
One script reply has been approved by the moderators Verified

Lists all R2 buckets on your account

Created by hugo697 174 days ago Viewed 5880 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 174 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * List Buckets
8
 * Lists all R2 buckets on your account
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  account_identifier: string,
13
  name_contains: string | undefined,
14
  start_after: string | undefined,
15
  per_page: string | undefined,
16
  order: "name" | undefined,
17
  direction: "asc" | "desc" | undefined,
18
  cursor: string | undefined
19
) {
20
  const url = new URL(
21
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/r2/buckets`
22
  );
23
  for (const [k, v] of [
24
    ["name_contains", name_contains],
25
    ["start_after", start_after],
26
    ["per_page", per_page],
27
    ["order", order],
28
    ["direction", direction],
29
    ["cursor", cursor],
30
  ]) {
31
    if (v !== undefined && v !== "") {
32
      url.searchParams.append(k, v);
33
    }
34
  }
35
  const response = await fetch(url, {
36
    method: "GET",
37
    headers: {
38
      "X-AUTH-EMAIL": auth.email,
39
      "X-AUTH-KEY": auth.key,
40
      Authorization: "Bearer " + auth.token,
41
    },
42
    body: undefined,
43
  });
44
  if (!response.ok) {
45
    const text = await response.text();
46
    throw new Error(`${response.status} ${text}`);
47
  }
48
  return await response.json();
49
}
50