Get analytics by time

Retrieves a list of aggregate metrics grouped by time interval.

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 by time
8
 * Retrieves a list of aggregate metrics grouped by time interval.
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
  time_delta:
20
    | "year"
21
    | "quarter"
22
    | "month"
23
    | "week"
24
    | "day"
25
    | "hour"
26
    | "dekaminute"
27
    | "minute"
28
    | undefined
29
) {
30
  const url = new URL(
31
    `https://api.cloudflare.com/client/v4/zones/${zone}/spectrum/analytics/events/bytime`
32
  );
33
  for (const [k, v] of [
34
    ["dimensions", dimensions],
35
    ["sort", sort],
36
    ["until", until],
37
    ["metrics", metrics],
38
    ["filters", filters],
39
    ["since", since],
40
    ["time_delta", time_delta],
41
  ]) {
42
    if (v !== undefined && v !== "") {
43
      url.searchParams.append(k, v);
44
    }
45
  }
46
  const response = await fetch(url, {
47
    method: "GET",
48
    headers: {
49
      "X-AUTH-EMAIL": auth.email,
50
      "X-AUTH-KEY": auth.key,
51
      Authorization: "Bearer " + auth.token,
52
    },
53
    body: undefined,
54
  });
55
  if (!response.ok) {
56
    const text = await response.text();
57
    throw new Error(`${response.status} ${text}`);
58
  }
59
  return await response.json();
60
}
61