Get a repository README for a directory

Gets the README from a repository directory. READMEs support [custom media types](https://docs.github.com/rest/reference/repos#custom-media-types) for retrieving the raw content or rendered HTML.

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
 * Get a repository README for a directory
6
 * Gets the README from a repository directory.
7

8
READMEs support [custom media types](https://docs.github.com/rest/reference/repos#custom-media-types) for retrieving the raw content or rendered HTML.
9
 */
10
export async function main(
11
  auth: Github,
12
  owner: string,
13
  repo: string,
14
  dir: string,
15
  ref: string | undefined
16
) {
17
  const url = new URL(
18
    `https://api.github.com/repos/${owner}/${repo}/readme/${dir}`
19
  );
20
  for (const [k, v] of [["ref", ref]]) {
21
    if (v !== undefined && v !== "") {
22
      url.searchParams.append(k, v);
23
    }
24
  }
25
  const response = await fetch(url, {
26
    method: "GET",
27
    headers: {
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.json();
37
}
38