aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/github/fetch_latest_artifact_metadata.ts
blob: 52641ca67d6e95ca92ed53771edef108f2a83d7e (plain)
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
import fetch from "node-fetch";

const GITHUB_API_ENDPOINT_URL = "https://api.github.com";

export interface FetchLatestArtifactMetadataOpts {
    repoName: string;
    repoOwner: string;
    artifactFileName: string;
}

export interface ArtifactMetadata {
    releaseName: string;
    releaseDate: Date;
    downloadUrl: string;
}

export async function fetchLatestArtifactMetadata(
    opts: FetchLatestArtifactMetadataOpts
): Promise<ArtifactMetadata | null> {

    const repoOwner = encodeURIComponent(opts.repoOwner);
    const repoName  = encodeURIComponent(opts.repoName);

    const apiEndpointPath = `/repos/${repoOwner}/${repoName}/releases/latest`;
    const requestUrl = GITHUB_API_ENDPOINT_URL + apiEndpointPath;

    // We skip runtime type checks for simplicity (here we cast from `any` to `Release`)

    const response: GithubRelease = await fetch(requestUrl, {
            headers: { Accept: "application/vnd.github.v3+json" }
        })
        .then(res => res.json());

    const artifact = response.assets.find(artifact => artifact.name === opts.artifactFileName);

    return !artifact ? null : {
        releaseName: response.name,
        releaseDate: new Date(response.published_at),
        downloadUrl: artifact.browser_download_url
    };

    // Noise denotes tremendous amount of data that we are not using here
    interface GithubRelease {
        name: string;
        published_at: Date;
        assets: Array<{
            browser_download_url: string;

            [noise: string]: unknown;
        }>;

        [noise: string]: unknown;
    }

}