/
index.ts
58 lines (53 loc) · 1.51 KB
/
index.ts
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
import { logger } from '../../../logger';
import { ExternalHostError } from '../../../types/errors/external-host-error';
import { GithubHttp } from '../../../util/http/github';
import { Preset, PresetConfig } from '../common';
import { PRESET_DEP_NOT_FOUND, fetchPreset } from '../util';
export const Endpoint = 'https://api.github.com/';
const http = new GithubHttp();
export async function fetchJSONFile(
repo: string,
fileName: string,
endpoint: string
): Promise<Preset> {
const url = `${endpoint}repos/${repo}/contents/${fileName}`;
let res: { body: { content: string } };
try {
res = await http.getJson(url);
} catch (err) {
// istanbul ignore if: not testable with nock
if (err instanceof ExternalHostError) {
throw err;
}
logger.debug(
{ statusCode: err.statusCode },
`Failed to retrieve ${fileName} from repo`
);
throw new Error(PRESET_DEP_NOT_FOUND);
}
try {
const content = Buffer.from(res.body.content, 'base64').toString();
const parsed = JSON.parse(content);
return parsed;
} catch (err) {
throw new Error('invalid preset JSON');
}
}
export async function getPresetFromEndpoint(
pkgName: string,
filePreset: string,
endpoint = Endpoint
): Promise<Preset> {
return fetchPreset({
pkgName,
filePreset,
endpoint,
fetch: fetchJSONFile,
});
}
export function getPreset({
packageName: pkgName,
presetName = 'default',
}: PresetConfig): Promise<Preset> {
return getPresetFromEndpoint(pkgName, presetName, Endpoint);
}