forked from withastro/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add retry logic to fetch (withastro#1303)
- Loading branch information
Showing
3 changed files
with
38 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,29 @@ | ||
import fetch from 'node-fetch'; | ||
import pRetry, { AbortError } from 'p-retry'; | ||
|
||
/** | ||
* Fetch a URL from the GitHub API and resolve its JSON response. | ||
* @param {{ url: string; githubToken?: string }} options | ||
* @returns {Promise<any>} | ||
*/ | ||
export async function githubGet({ url, githubToken = undefined }) { | ||
const headers = { | ||
Accept: 'application/vnd.github.v3+json', | ||
}; | ||
if (githubToken) { | ||
headers.Authorization = `token ${githubToken}`; | ||
} | ||
const response = await fetch(url, { | ||
headers, | ||
}); | ||
const json = await response.json(); | ||
return await pRetry( | ||
async () => { | ||
const headers = { | ||
Accept: 'application/vnd.github.v3+json', | ||
}; | ||
if (githubToken) { | ||
headers.Authorization = `token ${githubToken}`; | ||
} | ||
const response = await fetch(url, { headers }); | ||
const json = await response.json(); | ||
|
||
if (!response.ok) { | ||
throw new Error(`GitHub API call failed: GET "${url}" returned status ${response.status}: ${JSON.stringify(json)}`); | ||
} | ||
if (!response.ok) { | ||
throw new AbortError(`GitHub API call failed: GET "${url}" returned status ${response.status}: ${JSON.stringify(json)}`); | ||
} | ||
|
||
return json; | ||
return json; | ||
}, | ||
{ retries: 5 } | ||
); | ||
} |