Skip to content

Instantly share code, notes, and snippets.

@kenzauros
Created Jan 18, 2020
Embed
What would you like to do?
GitHub API で特定の user/organization のすべてのリポジトリ情報を取得する
const GITHUB_API_URL = 'https://api.github.com';
const GITHUB_TOKEN = '<GitHub API Token>';
// Prepare axios for GitHub API
const axiosBase = require('axios');
const github = axiosBase.create({
baseURL: GITHUB_API_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': `token ${GITHUB_TOKEN}`,
},
responseType: 'json',
});
/**
* Gets a list of repos in GitHub.
* @param {String} ownerType Resource type of owner (orgs|users)
* @param {String} owner Owner name
*/
async function getGithubRepos(ownerType, owner) {
let url = `${ownerType}/${owner}/repos?sort=full_name`;
const array = [];
while (url) {
const { next, data } = await getGithubReposPage(url);
if (data) array.push(data);
url = next;
}
return array.flat();
}
async function getGithubReposPage(url) {
const result = await github.get(url);
let next = null;
if (result.headers && result.headers.link) {
// extract next url from "link" header
const matches = /\<([^<>]+)\>; rel\="next"/.exec(result.headers.link);
if (matches) {
next = matches[1];
}
}
const data = result.data || null;
return {
next,
data,
};
}
// demo
(async () => {
const kenzaurosRepos = await getGithubRepos('users', 'kenzauros');
console.log(kenzaurosRepos);
const vuejsRepos = await getGithubRepos('orgs', 'vuejs');
console.log(vuejsRepos);
})();
{
"name": "github-api-list-all-repos",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.19.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment