Skip to content

Instantly share code, notes, and snippets.

@sstur
Forked from oshimayoan/asyncAwait.js
Last active February 21, 2017 09:23
Show Gist options
  • Save sstur/cf07615f0d762935f0473b5a636ae463 to your computer and use it in GitHub Desktop.
Save sstur/cf07615f0d762935f0473b5a636ae463 to your computer and use it in GitHub Desktop.
Fetching github users, orgs, and repos and print it.
// @flow
/* global fetch */
/* eslint-disable babel/no-await-in-loop */
type JSONData = null | string | number | boolean | {[key: string]: JSONData} | Array<JSONData>;
function handleResponseJSON(response: Response): Promise<JSONData> {
return response.json();
}
async function fetchUsers(userNames: Array<string>): Promise<*> {
console.log('Start fetching');
console.log('--------------');
for (let userName of userNames) {
let orgs = await fetch(`https://api.github.com/users/${userName}/orgs`).then(handleResponseJSON);
orgs = Array.isArray(orgs) ? orgs : [];
console.log('Fetching user..');
let orgsList = new Set();
for (let org of orgs) {
let orgName = (org && typeof org === 'object' && typeof org.login === 'string') ? org.login : '';
orgsList.add(orgName);
usersOrgs.set(userName, orgsList);
if (!orgsRepos.has(orgName)) {
let repos = await fetch(`https://api.github.com/orgs/${orgName}/repos`).then(handleResponseJSON);
let numRepos = Array.isArray(repos) ? repos.length : 0;
console.log('Fetching orgs..');
orgsRepos.set(orgName, numRepos);
}
}
}
console.log('Fetching done');
console.log('--------------');
return 1;
}
async function showUsers(userNames: Array<string>) {
let result = await fetchUsers(userNames); // eslint-disable-line
console.log('Start writing');
console.log('--------------');
usersOrgs.forEach((orgs: Set<string>, userName: string) => {
console.log(`${userName} member of ${orgs.size} orgs:`);
orgs.forEach((orgName: string) => {
let numRepos = orgsRepos.get(orgName) || 0;
console.log(`>> ${orgName} has ${numRepos}`);
});
});
console.log('--------------');
console.log('Writing done.');
}
let userNames = ['mjackson', 'sstur'];
let usersOrgs: Map<string, Set<string>> = new Map();
let orgsRepos: Map<string, number> = new Map();
showUsers(userNames);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment