Website for visualizing a persons github network.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

265 lines
6.5 KiB

5 years ago
  1. const routes = require('express').Router();
  2. const got = require("got");
  3. const cache = require('memory-cache');
  4. const dotenv = require("dotenv").config();
  5. const GITHUB_API = "https://api.github.com";
  6. const authenticate = `client_id=${process.env.CLIENT_ID}&client_secret=${process.env.CLIENT_SECRET}`;
  7. /**
  8. * Queries data from the github APi server and returns it as
  9. * a json object in a promise.
  10. *
  11. * This makes no attempt to cache
  12. *
  13. * @param {*} requestURL endpoint on githubapi: ex: /users/jrtechs/following
  14. */
  15. function queryGithubAPIRaw(requestURL)
  16. {
  17. return new Promise((resolve, reject)=>
  18. {
  19. var queryURL;
  20. if(requestURL.includes("?page="))
  21. {
  22. queryURL = GITHUB_API + requestURL + "&" + authenticate;
  23. }
  24. else
  25. {
  26. queryURL = GITHUB_API + requestURL + "?" + authenticate;
  27. }
  28. console.log(queryURL);
  29. got(queryURL, { json: true }).then(response =>
  30. {
  31. resolve(response.body);
  32. cache.put(requestURL, response.body);
  33. }).catch(error =>
  34. {
  35. resolve(error);
  36. cache.put(requestURL, error);
  37. });
  38. });
  39. }
  40. /**
  41. * Queries data from the github api server
  42. * and caches the results locally.
  43. *
  44. * @param {*} requestURL
  45. */
  46. function queryGitHubAPI(requestURL)
  47. {
  48. const apiData = cache.get(requestURL);
  49. return new Promise(function(resolve, reject)
  50. {
  51. if(apiData == null)
  52. {
  53. queryGithubAPIRaw(requestURL).then((dd)=>
  54. {
  55. resolve(dd);
  56. }).catch((err)=>
  57. {
  58. resolve(err);
  59. })
  60. }
  61. else
  62. {
  63. console.log("Fetched From Cache");
  64. resolve(apiData);
  65. }
  66. })
  67. }
  68. const API_FOLLOWING = "/following";
  69. const API_FOLLOWERS = "/followers";
  70. const API_USER_PATH = "/users/";
  71. const API_PAGINATION_SIZE = 100; // 100 is the max, 30 is the default
  72. // if this is too large, it would be infeasible to make graphs for people following popular people
  73. const API_MAX_PAGES = 3;
  74. const API_PAGINATION = "&per_page=" + API_PAGINATION_SIZE;
  75. /**
  76. * This will fetch all of the either followers or following of a
  77. * github user.
  78. *
  79. * This function is recursive to traverse all the pagination so we
  80. * can get a complete list of all the friends. The max amount of
  81. * followers/following you can get at once is 100.
  82. *
  83. * @param {*} username username of github client
  84. * @param {*} apiPath following or followers
  85. * @param {*} page current pagination page
  86. * @param {*} lst list we are building on
  87. */
  88. function fetchAllUsers(username, apiPath, page, lst)
  89. {
  90. return new Promise((resolve, reject)=>
  91. {
  92. queryGithubAPIRaw(API_USER_PATH + username + apiPath + "?page=" + page + API_PAGINATION).then((data)=>
  93. {
  94. if(data.hasOwnProperty("length"))
  95. {
  96. lst = lst.concat(data)
  97. if(page < API_MAX_PAGES && data.length === API_PAGINATION_SIZE)
  98. {
  99. fetchAllUsers(username, apiPath, page + 1, lst).then((l)=>
  100. {
  101. resolve(l);
  102. });
  103. }
  104. else
  105. {
  106. resolve(lst);
  107. }
  108. }
  109. else
  110. {
  111. reject("Malformed data");
  112. }
  113. }).catch((err)=>
  114. {
  115. reject("error with api request");
  116. });
  117. },
  118. (error)=>
  119. {
  120. if(error.hasOwnProperty("length"))
  121. {
  122. lst.concat(data);
  123. resolve(lst);
  124. }
  125. });
  126. }
  127. /**
  128. * Combines the list of friends and followers ignoring duplicates
  129. * that are already in the list. (person is both following and followed by someone)
  130. *
  131. * This also removes any unused properties like events_url and organizations_url
  132. *
  133. * @param {*} followingAndFollowers
  134. */
  135. function minimizeFriends(people)
  136. {
  137. var friendLst = [];
  138. var ids = new Set();
  139. for(var i = 0; i < people.length; i++)
  140. {
  141. if(!ids.has(people[i].id))
  142. {
  143. ids.add(people[i].id);
  144. friendLst.push({
  145. id: people[i].id,
  146. login: people[i].login,
  147. avatar_url: people[i].avatar_url
  148. });
  149. }
  150. }
  151. return friendLst;
  152. }
  153. /**
  154. * Fetches all the people that are either following or is followed
  155. * by a person on github. This will cache the results to make simultaneous
  156. * connections easier and less demanding on the github API.
  157. *
  158. * @param {*} user
  159. */
  160. function queryFriends(user)
  161. {
  162. const cacheHit = cache.get("/friends/" + user);
  163. return new Promise((resolve, reject)=>
  164. {
  165. if(cacheHit == null)
  166. {
  167. fetchAllUsers(user, API_FOLLOWERS, 1, []).then((followers)=>
  168. {
  169. fetchAllUsers(user, API_FOLLOWING, 1, []).then((following)=>
  170. {
  171. var fList = minimizeFriends(following.concat(followers));
  172. resolve(fList);
  173. cache.put("/friends/" + user, fList);
  174. }).catch((err)=>
  175. {
  176. console.log(err);
  177. })
  178. }).catch((error)=>
  179. {
  180. console.log(error);
  181. })
  182. }
  183. else
  184. {
  185. console.log("Friends cache hit");
  186. resolve(cacheHit);
  187. }
  188. });
  189. }
  190. routes.get("/friends/:name", (request, result)=>
  191. {
  192. queryFriends(request.params.name).then(friends=>
  193. {
  194. result.json(friends)
  195. .end();
  196. }).catch(error=>
  197. {
  198. result.status(500)
  199. .json({error: 'API error fetching friends'})
  200. .end();
  201. });
  202. })
  203. routes.get('/*', (request, result) =>
  204. {
  205. var gitHubAPIURL = request.url;
  206. result.setHeader('Content-Type', 'application/json');
  207. queryGitHubAPI(gitHubAPIURL).then((data)=>
  208. {
  209. if(data.hasOwnProperty("id") || data[0].hasOwnProperty("id"))
  210. {
  211. result.write(JSON.stringify(data));
  212. }
  213. else
  214. {
  215. result.write("[]");
  216. }
  217. result.end();
  218. }).catch((error)=>
  219. {
  220. try
  221. {
  222. if(error.hasOwnProperty("id") || error[0].hasOwnProperty("id"))
  223. {
  224. result.write(JSON.stringify(error));
  225. }
  226. else
  227. {
  228. result.write("[]");
  229. }
  230. }
  231. catch(error)
  232. {
  233. result.write("[]");
  234. };
  235. result.end();
  236. });
  237. if(cache.size() > 50000)
  238. {
  239. cache.clear();
  240. }
  241. });
  242. module.exports = routes;