0
Get Dataset csv Stream
One script reply has been approved by the moderators Verified

Get the csv content of a given dataset by alias or id. When getting the content by alias the latest dataset is returned, optionally filtered by the latest available at a given date.

Created by hugo697 411 days ago Viewed 9956 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 411 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Get Dataset csv Stream
8
 * Get the csv content of a given dataset by alias or id. When getting the content by alias the latest dataset is returned, optionally filtered by the latest available at a given date.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  alias: string,
13
  date: string | undefined
14
) {
15
  const url = new URL(
16
    `https://api.cloudflare.com/client/v4/radar/datasets/${alias}`
17
  );
18
  for (const [k, v] of [["date", date]]) {
19
    if (v !== undefined && v !== "") {
20
      url.searchParams.append(k, v);
21
    }
22
  }
23
  const response = await fetch(url, {
24
    method: "GET",
25
    headers: {
26
      "X-AUTH-EMAIL": auth.email,
27
      "X-AUTH-KEY": auth.key,
28
      Authorization: "Bearer " + auth.token,
29
    },
30
    body: undefined,
31
  });
32
  if (!response.ok) {
33
    const text = await response.text();
34
    throw new Error(`${response.status} ${text}`);
35
  }
36
  return await response.text();
37
}
38