1
+ const id = "YOUR_CLIENT_ID" ;
2
+ const sec = "YOUR_SECRET_ID" ;
3
+ const params = `?client_id=${ id } &client_secret=${ sec } ` ;
4
+
1
5
export function fetchPopularRepos ( language ) {
2
6
const endpoint = window . encodeURI (
3
7
`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) {
13
17
return data . items ;
14
18
} ) ;
15
19
}
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