Skip to content

Commit 32da752

Browse files
committed
11-api
1 parent 556c0e6 commit 32da752

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

app/components/Results.jsx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
11
import * as React from "react";
2+
import { battle } from "../utils/api";
23

34
export default class Results extends React.Component {
5+
componentDidMount() {
6+
const { playerOne, playerTwo } = this.props;
7+
8+
battle([playerOne, playerTwo]).then((players) => {
9+
console.log("data", players);
10+
});
11+
}
412
render() {
513
return (
614
<div>

app/utils/api.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
const id = "YOUR_CLIENT_ID";
2+
const sec = "YOUR_SECRET_ID";
3+
const params = `?client_id=${id}&client_secret=${sec}`;
4+
15
export function fetchPopularRepos(language) {
26
const endpoint = window.encodeURI(
37
`https://api.github.com/search/repositories?q=stars:>1+language:${language}&sort=stars&order=desc&type=Repositories`
@@ -13,3 +17,66 @@ export function fetchPopularRepos(language) {
1317
return data.items;
1418
});
1519
}
20+
21+
function getErrorMsg(message, username) {
22+
if (message === "Not Found") {
23+
return `${username} doesn't exist`;
24+
}
25+
26+
return message;
27+
}
28+
29+
function getProfile(username) {
30+
return fetch(`https://api.github.com/users/${username}${params}`)
31+
.then((res) => res.json())
32+
.then((profile) => {
33+
if (profile.message) {
34+
throw new Error(getErrorMsg(profile.message, username));
35+
}
36+
37+
return profile;
38+
});
39+
}
40+
41+
function getRepos(username) {
42+
return fetch(
43+
`https://api.github.com/users/${username}/repos${params}&per_page=100`
44+
)
45+
.then((res) => res.json())
46+
.then((repos) => {
47+
if (repos.message) {
48+
throw new Error(getErrorMsg(repos.message, username));
49+
}
50+
51+
return repos;
52+
});
53+
}
54+
55+
function getStarCount(repos) {
56+
return repos.reduce((count, { stargazers_count }) => {
57+
return count + stargazers_count;
58+
}, 0);
59+
}
60+
61+
function calculateScore(followers, repos) {
62+
return followers * 3 + getStarCount(repos);
63+
}
64+
65+
function getUserData(player) {
66+
return Promise.all([getProfile(player), getRepos(player)]).then(
67+
([profile, repos]) => ({
68+
profile,
69+
score: calculateScore(profile.followers, repos),
70+
})
71+
);
72+
}
73+
74+
function sortPlayers(players) {
75+
return players.sort((a, b) => b.score - a.score);
76+
}
77+
78+
export function battle(players) {
79+
return Promise.all([getUserData(players[0]), getUserData(players[1])]).then(
80+
sortPlayers
81+
);
82+
}

0 commit comments

Comments
 (0)