Skip to content

Commit

Permalink
Add retry logic to fetch (withastro#1303)
Browse files Browse the repository at this point in the history
  • Loading branch information
delucis authored Aug 16, 2022
1 parent e8910fe commit 6737473
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 14 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"htmlparser2": "^7.2.0",
"kleur": "^4.1.5",
"node-fetch": "^3.2.10",
"p-retry": "^5.1.1",
"parse-numeric-range": "^1.3.0",
"preact": "^10.10.1",
"prettier": "^2.7.1",
Expand Down
19 changes: 19 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 18 additions & 14 deletions scripts/lib/github-get.mjs
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 }
);
}

0 comments on commit 6737473

Please sign in to comment.