Last active
October 7, 2020 18:48
-
-
Save kristoferjoseph/5d646d5aa28d8166eb079439dafc0d7b to your computer and use it in GitHub Desktop.
List all repos for an organization using the GitHub API and pagination Link header.
This file contains hidden or 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>GET ALL REPOS</title> | |
<style> | |
* { | |
margin:0; | |
padding:0; | |
box-sizing: border-box; | |
} | |
html { | |
font-size: 20px; | |
} | |
body { | |
font-family: sans-serif; | |
} | |
#root { | |
padding: 2rem; | |
} | |
</style> | |
</head> | |
<body> | |
<pre> | |
<code id=root> | |
</code> | |
</pre> | |
<script type=module> | |
(async function(){ | |
const page = 0 | |
const per = 10 // Default is 30, max is 100 | |
const token = YOUR_GITHUB_TOKEN_HERE | |
const org = YOUR_ORG_NAME_HERE | |
const template = (page, per) => `https://api.github.com/orgs/${org}/repos?page=${page}&per_page=${per}` | |
async function fetchPage(params={}) { | |
let { page, per, template, token } = params | |
let url = template(page, per) | |
let headers = { | |
'Content-Type': 'application/json', | |
Authorization: `token ${token}`, | |
Accept: 'application/vnd.github.v3+json' | |
} | |
let responseHeaders | |
let result | |
try { | |
let response = await fetch(url, { headers }) | |
responseHeaders = parseLink(response.headers.get('Link')) | |
result = await response.json() | |
} | |
catch(err) { | |
console.error(err) | |
} | |
return { | |
result, | |
last: responseHeaders.last | |
} | |
} | |
async function getRepos(params) { | |
let { name, page, per, template, token } = params | |
var repos = [] | |
let next = true | |
while(next) { | |
let { result, last } = await fetchPage({ page: page++, per, template, token }) | |
repos = repos.concat(result) | |
// If there is no last link in the Link Headers stop then exit the while loop | |
next = last | |
} | |
return repos | |
} | |
function parseLink(s) { | |
const output = {} | |
const regex = /<([^>]+)>; rel="([^"]+)"/g | |
let match | |
while (match = regex.exec(s)) { | |
let value = match[1] | |
let key = match[2] | |
output[key] = value | |
} | |
return output | |
} | |
let repos = await getRepos({ name, page, per, template, token }) | |
let root = document.getElementById('root') | |
root.innerHTML = JSON.stringify(repos, null, 2) | |
}()) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment