From abe0005f807e9653feab30b6af9fb0bd376ce978 Mon Sep 17 00:00:00 2001 From: Sam Becker Date: Sun, 16 Feb 2025 11:11:34 -0600 Subject: [PATCH] Screen for GitHub errors --- src/platforms/github.ts | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/src/platforms/github.ts b/src/platforms/github.ts index d67486cf..bf072e64 100644 --- a/src/platforms/github.ts +++ b/src/platforms/github.ts @@ -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 => { - 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,