0
Get Dataset download url
One script reply has been approved by the moderators Verified

Get a url to download a single dataset.

Created by hugo697 151 days ago Viewed 3723 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 151 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Get Dataset download url
8
 * Get a url to download a single dataset.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  format: "JSON" | "CSV" | undefined,
13
  body: { datasetId: number; [k: string]: unknown }
14
) {
15
  const url = new URL(
16
    `https://api.cloudflare.com/client/v4/radar/datasets/download`
17
  );
18
  for (const [k, v] of [["format", format]]) {
19
    if (v !== undefined && v !== "") {
20
      url.searchParams.append(k, v);
21
    }
22
  }
23
  const response = await fetch(url, {
24
    method: "POST",
25
    headers: {
26
      "X-AUTH-EMAIL": auth.email,
27
      "X-AUTH-KEY": auth.key,
28
      "Content-Type": "application/json",
29
      Authorization: "Bearer " + auth.token,
30
    },
31
    body: JSON.stringify(body),
32
  });
33
  if (!response.ok) {
34
    const text = await response.text();
35
    throw new Error(`${response.status} ${text}`);
36
  }
37
  return await response.json();
38
}
39