0

Get page views

by
Published Oct 25, 2023

Get the total number of views and breakdown per day or week for the last 14 days. Timestamps are aligned to UTC midnight of the beginning of the day or week. Week begins on Monday.

Script github Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 398 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * Get page views
6
 * Get the total number of views and breakdown per day or week for the last 14 days. Timestamps are aligned to UTC midnight of the beginning of the day or week. Week begins on Monday.
7
 */
8
export async function main(
9
  auth: Github,
10
  owner: string,
11
  repo: string,
12
  per: "day" | "week" | undefined
13
) {
14
  const url = new URL(
15
    `https://api.github.com/repos/${owner}/${repo}/traffic/views`
16
  );
17
  for (const [k, v] of [["per", per]]) {
18
    if (v !== undefined && v !== "") {
19
      url.searchParams.append(k, v);
20
    }
21
  }
22
  const response = await fetch(url, {
23
    method: "GET",
24
    headers: {
25
      Authorization: "Bearer " + auth.token,
26
    },
27
    body: undefined,
28
  });
29
  if (!response.ok) {
30
    const text = await response.text();
31
    throw new Error(`${response.status} ${text}`);
32
  }
33
  return await response.json();
34
}
35