Get analytics summary

Retrieves a list of summarised aggregate metrics over a given time period.

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
 * Get analytics summary
8
 * Retrieves a list of summarised aggregate metrics over a given time period.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  zone: string,
13
  dimensions: string | undefined,
14
  sort: string | undefined,
15
  until: string | undefined,
16
  metrics: string | undefined,
17
  filters: string | undefined,
18
  since: string | undefined
19
) {
20
  const url = new URL(
21
    `https://api.cloudflare.com/client/v4/zones/${zone}/spectrum/analytics/events/summary`
22
  );
23
  for (const [k, v] of [
24
    ["dimensions", dimensions],
25
    ["sort", sort],
26
    ["until", until],
27
    ["metrics", metrics],
28
    ["filters", filters],
29
    ["since", since],
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