fetch-repos.js in JavaScript
Fetch a user's repos concurrently and rank them by stars.
#!/usr/bin/env node
// Fetch a user's public repos concurrently and print the busiest ones.
const API = "https://api.github.com";
async function getJson(url) {
const response = await fetch(url, {
headers: { Accept: "application/vnd.github+json" },
});
if (!response.ok) {
throw new Error(`${url} -> ${response.status}`);
}
return response.json();
}
async function main() {
const user = process.argv[2] ?? "torvalds";
const repos = await getJson(`${API}/users/${user}/repos?per_page=10`);
const detailed = await Promise.all(
repos.map((repo) => getJson(`${API}/repos/${repo.full_name}`)),
);
const busiest = detailed
.sort((a, b) => b.stargazers_count - a.stargazers_count)
.slice(0, 5);
console.log(`top repos for ${user}:`);
for (const repo of busiest) {
const stars = String(repo.stargazers_count).padStart(7);
console.log(`${stars} ${repo.name} (${repo.language ?? "n/a"})`);
}
}
main().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
How it works
getJsonwraps fetch with header and status checks.Promise.allloads every repo's detail at once.- Sorting by stars prints the busiest five.
Keywords and builtins used here
PromiseStringasyncawaitcatchconstforfunctionifofreturnthrow
The run, in numbers
- Lines
- 38
- Characters to type
- 972
- Tokens
- 259
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 141 seconds.
Step 1 of 1 in Encore, step 19 of 19 in Promises & async.