87 lines
1.9 KiB
JavaScript
87 lines
1.9 KiB
JavaScript
import axios from "axios";
|
|
|
|
const id = "b2226ece2b6fce3bb116";
|
|
const sec = "be0525b65ff757d7e70e19589655fe5a41d4e2aa";
|
|
const param = `?client_id=${id}&client_secret=${sec}`;
|
|
|
|
function getUserInfo(username) {
|
|
return axios.get(`https://api.github.com/users/${username}${param}`);
|
|
}
|
|
|
|
/**
|
|
* Fetch repos for username.
|
|
*
|
|
* @param username
|
|
*/
|
|
function getRepos(username) {
|
|
return axios.get(`https://api.github.com/users/${username}/repos${param}&per_page=100`);
|
|
}
|
|
|
|
/**
|
|
* Calculate all the stars that the user has.
|
|
*
|
|
* @param repos
|
|
*/
|
|
function getTotalStars(repos) {
|
|
console.log("getTotalStars, repos", repos);
|
|
return repos.data.reduce((accu, repo) => {
|
|
return accu + repo.stargazers_count;
|
|
}, 0);
|
|
}
|
|
|
|
/**
|
|
* Get repos, get total stars, return object with these data.
|
|
*
|
|
* @param player
|
|
*/
|
|
function getPlayersData(player) {
|
|
return getRepos(player.login)
|
|
.then(getTotalStars)
|
|
.then((totalStars) => {
|
|
return {
|
|
followers: player.followers,
|
|
totalStars
|
|
};
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Return an array after doing some fancy calculation to determine a winner.
|
|
*
|
|
* @param players
|
|
*/
|
|
function calculateScores(players) {
|
|
return [
|
|
players[0].followers * 3 + players[0].totalStars,
|
|
players[1].followers * 3 + players[1].totalStars
|
|
];
|
|
}
|
|
|
|
const helpers = {
|
|
battle(players) {
|
|
const playerOneData = getPlayersData(players[0]);
|
|
const playerTwoData = getPlayersData(players[1]);
|
|
|
|
return axios.all([playerOneData, playerTwoData])
|
|
.then(calculateScores)
|
|
.catch((err) => {
|
|
console.warn("Battle getPlayersData error", err);
|
|
});
|
|
},
|
|
|
|
getPlayersInfo(players) {
|
|
// fetch some data from Github
|
|
return axios.all(players.map((username) => {
|
|
return getUserInfo(username);
|
|
})).then((info) => {
|
|
return info.map((item) => {
|
|
return item.data;
|
|
});
|
|
}).catch((err) => {
|
|
console.warn("Error in getPlayerInfo", err);
|
|
});
|
|
}
|
|
};
|
|
|
|
|
|
export default helpers;
|