-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrawFile.ts
More file actions
73 lines (63 loc) · 1.9 KB
/
rawFile.ts
File metadata and controls
73 lines (63 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Import Internal Dependencies
import {
DEFAULT_USER_AGENT,
GITHUB_RAW_API
} from "../constants.ts";
import type { RequestConfig } from "../types.ts";
// CONSTANTS
const kDefaultRef = "HEAD";
export interface FetchRawFileOptions extends RequestConfig {
/**
* Branch, tag, or commit SHA.
* @default "HEAD"
*/
ref?: string;
}
export type FetchRawFileClientOptions = Omit<FetchRawFileOptions, "token" | "userAgent">;
export type RawFileParser<T> = "json" | ((content: string) => T);
export function fetchRawFile(
repository: `${string}/${string}`,
filePath: string,
options?: FetchRawFileOptions & { parser?: undefined; }
): Promise<string>;
export function fetchRawFile<T = unknown>(
repository: `${string}/${string}`,
filePath: string,
options: FetchRawFileOptions & { parser: "json"; }
): Promise<T>;
export function fetchRawFile<T>(
repository: `${string}/${string}`,
filePath: string,
options: FetchRawFileOptions & { parser: (content: string) => T; }
): Promise<T>;
export async function fetchRawFile<T>(
repository: `${string}/${string}`,
filePath: string,
options: FetchRawFileOptions & { parser?: RawFileParser<T>; } = {}
): Promise<string | T> {
const {
ref = kDefaultRef,
token,
userAgent = DEFAULT_USER_AGENT,
parser
} = options;
const url = new URL(`${repository}/${ref}/${filePath}`, GITHUB_RAW_API);
const headers: Record<string, string> = {
"User-Agent": userAgent,
...(typeof token === "string" ? { Authorization: `token ${token}` } : {})
};
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(
`Failed to fetch raw file '${filePath}' from ${repository}@${ref}: HTTP ${response.status}`
);
}
const content = await response.text();
if (parser === "json") {
return JSON.parse(content) as T;
}
if (typeof parser === "function") {
return parser(content);
}
return content;
}