-
Notifications
You must be signed in to change notification settings - Fork 301
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Robert Tyree
committed
Dec 20, 2021
1 parent
a9a1c60
commit 5406c2d
Showing
1 changed file
with
44 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
'use strict'; | ||
|
||
const fetch = require('node-fetch'); | ||
const parseLinkHeader = require('parse-link-header'); | ||
|
||
/** | ||
* Pulls the next page off of a `Link` header | ||
* @param {String} linkHeader the `Link` header value | ||
* @returns {String|Null} the next page of results | ||
*/ | ||
const getNextLink = (linkHeader) => { | ||
const parsedLinkHeader = parseLinkHeader(linkHeader); | ||
if (parsedLinkHeader && parsedLinkHeader.next) { | ||
return parsedLinkHeader.next.url || null; | ||
} | ||
return null; | ||
}; | ||
|
||
/** | ||
* Fetches paginated results from the Github API | ||
* @param {String} url the API to query | ||
* @param {String} token a token for the API | ||
* @returns {Promise<Object[]>} all pages of results | ||
*/ | ||
const fetchPaginatedGHResults = async (url, token) => { | ||
let files = []; | ||
let nextPageLink = url; | ||
while (nextPageLink) { | ||
const resp = await fetch(nextPageLink, { | ||
headers: { authorization: `token ${token}` }, | ||
}); | ||
if (!resp.ok) { | ||
throw new Error( | ||
`Github API returned status ${resp.code} - ${resp.message}` | ||
); | ||
} | ||
const page = await resp.json(); | ||
nextPageLink = getNextLink(resp.headers.get('Link')); | ||
files = [...files, ...page]; | ||
} | ||
return files; | ||
}; | ||
|
||
module.exports = { fetchPaginatedGHResults, getNextLink }; |