Screen for GitHub errors

This commit is contained in:
Sam Becker 2025-02-16 11:11:34 -06:00
parent 0e1028a7e5
commit abe0005f80

View File

@ -6,10 +6,11 @@ import {
const DEFAULT_BRANCH = 'main';
const CACHE_GITHUB_REQUESTS = false;
const GITHUB_API_ERROR = 'API rate limit exceeded';
// Cache all results for 2 minutes to avoid rate limiting
// GitHub API requests limited to 60 requests per hour
const FETCH_CONFIG: RequestInit | undefined= CACHE_GITHUB_REQUESTS
const FETCH_CONFIG: RequestInit | undefined = CACHE_GITHUB_REQUESTS
? { next: { revalidate: 120 } } : undefined;
interface RepoParams {
@ -19,6 +20,18 @@ interface RepoParams {
commit?: string
};
const fetchGitHub = async (url: string, cacheRequest?: boolean) => {
const data = await fetch(
url,
cacheRequest ? { next: { revalidate: 120 } } : undefined,
)
.then(response => response.json());
if ((data.message ?? '').includes(GITHUB_API_ERROR)) {
throw new Error(GITHUB_API_ERROR);
}
return data;
};
// Website urls
export const getGitHubUrlOwner = ({
@ -90,8 +103,7 @@ export const getLatestBaseRepoCommitSha = async () => {
};
const getIsRepoForkedFromBase = async (params: RepoParams) => {
const response = await fetch(getGitHubApiRepoUrl(params), FETCH_CONFIG);
const data = await response.json();
const data = await fetchGitHub(getGitHubApiRepoUrl(params));
console.log('getIsRepoForkedFromBase', { data });
return (
Boolean(data.fork) &&
@ -100,20 +112,12 @@ const getIsRepoForkedFromBase = async (params: RepoParams) => {
};
const getGitHubCommitsBehindFromRepo = async (params?: RepoParams) => {
const response = await fetch(
getGitHubApiCompareToRepoUrl(params),
FETCH_CONFIG,
);
const data = await response.json();
const data = await fetchGitHub(getGitHubApiCompareToRepoUrl(params));
return data.behind_by as number;
};
const getGitHubCommitsBehindFromCommit = async (params?: RepoParams) => {
const response = await fetch(
getGitHubApiCompareToCommitUrl(params),
FETCH_CONFIG,
);
const data = await response.json();
const data = await fetchGitHub(getGitHubApiCompareToCommitUrl(params));
return data.behind_by as number;
};
@ -122,8 +126,8 @@ const isRepoBaseRepo = ({ owner, repo }: RepoParams) =>
repo?.toLowerCase() === TEMPLATE_REPO_NAME;
export const getGitHubPublicFork = async (): Promise<RepoParams> => {
const response = await fetch(getGitHubApiForksUrl(), FETCH_CONFIG);
const fork = (await response.json())[0];
const data = await fetchGitHub(getGitHubApiForksUrl());
const fork = data[0];
return {
owner: fork?.owner.login,
repo: fork?.name,