List repositories for the authenticated user

Lists repositories that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access. The authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership.

Script github Verified

by hugo697 ยท 10/25/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 367 days ago
1
type Github = {
2
  token: string;
3
};
4
/**
5
 * List repositories for the authenticated user
6
 * Lists repositories that the authenticated user has explicit permission (`:read`, `:write`, or `:admin`) to access.
7

8
The authenticated user has explicit permission to access repositories they own, repositories where they are a collaborator, and repositories that they can access through an organization membership.
9
 */
10
export async function main(
11
  auth: Github,
12
  visibility: "all" | "public" | "private" | undefined,
13
  affiliation: string | undefined,
14
  type: "all" | "owner" | "public" | "private" | "member" | undefined,
15
  sort: "created" | "updated" | "pushed" | "full_name" | undefined,
16
  direction: "asc" | "desc" | undefined,
17
  per_page: string | undefined,
18
  page: string | undefined,
19
  since: string | undefined,
20
  before: string | undefined
21
) {
22
  const url = new URL(`https://api.github.com/user/repos`);
23
  for (const [k, v] of [
24
    ["visibility", visibility],
25
    ["affiliation", affiliation],
26
    ["type", type],
27
    ["sort", sort],
28
    ["direction", direction],
29
    ["per_page", per_page],
30
    ["page", page],
31
    ["since", since],
32
    ["before", before],
33
  ]) {
34
    if (v !== undefined && v !== "") {
35
      url.searchParams.append(k, v);
36
    }
37
  }
38
  const response = await fetch(url, {
39
    method: "GET",
40
    headers: {
41
      Authorization: "Bearer " + auth.token,
42
    },
43
    body: undefined,
44
  });
45
  if (!response.ok) {
46
    const text = await response.text();
47
    throw new Error(`${response.status} ${text}`);
48
  }
49
  return await response.json();
50
}
51