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.

365 lines
8.8 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. const API_FOLLOWING = "/following";
  8. const API_FOLLOWERS = "/followers";
  9. const API_USER_PATH = "/users/";
  10. const API_ORGS_PATH = "/orgs/";
  11. const API_PAGINATION_SIZE = 100; // 100 is the max, 30 is the default
  12. // if this is too large, it would be infeasible to make graphs for people following popular people
  13. const API_MAX_PAGES = 2;
  14. const API_PAGINATION = "&per_page=" + API_PAGINATION_SIZE;
  15. const REPOS_PATH = "/repos";
  16. /**
  17. * Queries data from the github APi server and returns it as
  18. * a json object in a promise.
  19. *
  20. * This makes no attempt to cache
  21. *
  22. * @param {*} requestURL endpoint on githubapi: ex: /users/jrtechs/following
  23. */
  24. function queryGithubAPIRaw(requestURL)
  25. {
  26. return new Promise((resolve, reject)=>
  27. {
  28. var queryURL;
  29. if(requestURL.includes("?page="))
  30. {
  31. queryURL = GITHUB_API + requestURL + "&" + authenticate;
  32. }
  33. else
  34. {
  35. queryURL = GITHUB_API + requestURL + "?" + authenticate;
  36. }
  37. console.log(queryURL);
  38. got(queryURL, { json: true }).then(response =>
  39. {
  40. resolve(response.body);
  41. cache.put(requestURL, response.body);
  42. }).catch(error =>
  43. {
  44. resolve(error);
  45. cache.put(requestURL, error);
  46. });
  47. });
  48. }
  49. /**
  50. * Queries data from the github api server
  51. * and caches the results locally.
  52. *
  53. * @param {*} requestURL
  54. */
  55. function queryGitHubAPI(requestURL)
  56. {
  57. const apiData = cache.get(requestURL);
  58. return new Promise(function(resolve, reject)
  59. {
  60. if(apiData == null)
  61. {
  62. queryGithubAPIRaw(requestURL).then((dd)=>
  63. {
  64. resolve(dd);
  65. }).catch((err)=>
  66. {
  67. resolve(err);
  68. })
  69. }
  70. else
  71. {
  72. console.log("Fetched From Cache");
  73. resolve(apiData);
  74. }
  75. })
  76. }
  77. /**
  78. * Fetches all content from a particular github api endpoint
  79. * using their pagination schema.
  80. *
  81. * @param {*} username username of github client
  82. * @param {*} apiPath following or followers
  83. * @param {*} page current pagination page
  84. * @param {*} lst list we are building on
  85. */
  86. function fetchAllWithPagination(apiPath, page, lst)
  87. {
  88. return new Promise((resolve, reject)=>
  89. {
  90. queryGithubAPIRaw(apiPath + "?page=" + page + API_PAGINATION).then((data)=>
  91. {
  92. if(data.hasOwnProperty("length"))
  93. {
  94. lst = lst.concat(data)
  95. if(page < API_MAX_PAGES && data.length === API_PAGINATION_SIZE)
  96. {
  97. fetchAllWithPagination(apiPath, page + 1, lst).then((l)=>
  98. {
  99. resolve(l);
  100. });
  101. }
  102. else
  103. {
  104. resolve(lst);
  105. }
  106. }
  107. else
  108. {
  109. console.log(data);
  110. reject("Malformed data");
  111. }
  112. }).catch((err)=>
  113. {
  114. reject("error with api request");
  115. });
  116. },
  117. (error)=>
  118. {
  119. if(error.hasOwnProperty("length"))
  120. {
  121. lst.concat(data);
  122. resolve(lst);
  123. }
  124. });
  125. }
  126. /**
  127. * Makes a copy of a JS object with certain properties
  128. *
  129. * @param {*} props
  130. * @param {*} obj
  131. */
  132. function copyWithProperties(props, obj)
  133. {
  134. var newO = new Object();
  135. for(var i =0; i < props.length; i++)
  136. {
  137. newO[props[i]] = obj[props[i]];
  138. }
  139. return newO;
  140. }
  141. /**
  142. * Combines the list of friends and followers ignoring duplicates
  143. * that are already in the list. (person is both following and followed by someone)
  144. *
  145. * This also removes any unused properties like events_url and organizations_url
  146. *
  147. * @param {*} followingAndFollowers
  148. */
  149. function minimizeFriends(people)
  150. {
  151. var friendLst = [];
  152. var ids = new Set();
  153. for(var i = 0; i < people.length; i++)
  154. {
  155. if(!ids.has(people[i].id))
  156. {
  157. ids.add(people[i].id);
  158. friendLst.push({
  159. login: people[i].login,
  160. avatar_url: people[i].avatar_url
  161. });
  162. }
  163. }
  164. return friendLst;
  165. }
  166. /**
  167. * Fetches all the people that are either following or is followed
  168. * by a person on github. This will cache the results to make simultaneous
  169. * connections easier and less demanding on the github API.
  170. *
  171. * @param {*} user
  172. */
  173. function queryFriends(user)
  174. {
  175. const cacheHit = cache.get("/friends/" + user);
  176. return new Promise((resolve, reject)=>
  177. {
  178. if(cacheHit == null)
  179. {
  180. fetchAllWithPagination(API_USER_PATH + user + API_FOLLOWERS, 1, []).then((followers)=>
  181. {
  182. fetchAllWithPagination(API_USER_PATH + user + API_FOLLOWING, 1, []).then((following)=>
  183. {
  184. var fList = minimizeFriends(following.concat(followers));
  185. resolve(fList);
  186. cache.put("/friends/" + user, fList);
  187. }).catch((err)=>
  188. {
  189. console.log(err);
  190. reject("API ERROR");
  191. })
  192. }).catch((error)=>
  193. {
  194. console.log(error);
  195. resolve("API Error");
  196. })
  197. }
  198. else
  199. {
  200. console.log("Friends cache hit");
  201. resolve(cacheHit);
  202. }
  203. });
  204. }
  205. /**
  206. * Minimizes the JSON for a list of repositories
  207. *
  208. * @param {*} repositories
  209. */
  210. function minimizeRepositories(repositories)
  211. {
  212. var rList = [];
  213. for(var i = 0; i < repositories.length; i++)
  214. {
  215. rList.push(copyWithProperties(["name", "created_at", "homepage",
  216. "description", "language", "forks", "watchers",
  217. "open_issues_count", "license", "html_url"],
  218. repositories[i]));
  219. }
  220. return rList;
  221. }
  222. /**
  223. * Fetches all repositories from the API
  224. *
  225. * @param {*} user name of org/user
  226. * @param {*} orgsOrUsers either /users/ or /orgs/
  227. */
  228. function queryRepositories(user, orgsOrUsers)
  229. {
  230. const cacheHit = cache.get(user + REPOS_PATH);
  231. return new Promise((resolve, reject)=>
  232. {
  233. if(cacheHit == null)
  234. {
  235. fetchAllWithPagination(orgsOrUsers + user + REPOS_PATH, 1, []).then((repos)=>
  236. {
  237. var minimized = minimizeRepositories(repos);
  238. resolve(minimized);
  239. cache.put(user + REPOS_PATH, minimized);
  240. }).catch((err)=>
  241. {
  242. console.log(err)
  243. console.log("bad things went down");
  244. })
  245. }
  246. else
  247. {
  248. console.log("Repositories cache hit");
  249. resolve(cacheHit);
  250. }
  251. });
  252. }
  253. routes.get("/friends/:name", (request, result)=>
  254. {
  255. queryFriends(request.params.name).then(friends=>
  256. {
  257. result.json(friends)
  258. .end();
  259. }).catch(error=>
  260. {
  261. result.status(500)
  262. .json({error: 'API error fetching friends'})
  263. .end();
  264. });
  265. });
  266. routes.get("/repositories/:name", (request, result)=>
  267. {
  268. queryRepositories(request.params.name, API_USER_PATH).then(repos=>
  269. {
  270. result.json(repos)
  271. .end();
  272. }).catch(error=>
  273. {
  274. result.status(500)
  275. .json({error: 'API error fetching friends'})
  276. .end();
  277. });
  278. });
  279. routes.get("/org/repositories/:name", (request, result)=>
  280. {
  281. queryRepositories(request.params.name, API_ORGS_PATH).then(repos=>
  282. {
  283. result.json(repos)
  284. .end();
  285. }).catch(error=>
  286. {
  287. result.status(500)
  288. .json({error: 'API error fetching friends'})
  289. .end();
  290. });
  291. });
  292. routes.get('/*', (request, result) =>
  293. {
  294. var gitHubAPIURL = request.url;
  295. result.setHeader('Content-Type', 'application/json');
  296. queryGitHubAPI(gitHubAPIURL).then((data)=>
  297. {
  298. if(data.hasOwnProperty("id") || data[0].hasOwnProperty("id"))
  299. {
  300. result.write(JSON.stringify(data));
  301. }
  302. else
  303. {
  304. result.write("[]");
  305. }
  306. result.end();
  307. }).catch((error)=>
  308. {
  309. try
  310. {
  311. if(error.hasOwnProperty("id") || error[0].hasOwnProperty("id"))
  312. {
  313. result.write(JSON.stringify(error));
  314. }
  315. else
  316. {
  317. result.write("[]");
  318. }
  319. }
  320. catch(error)
  321. {
  322. result.write("[]");
  323. };
  324. result.end();
  325. });
  326. if(cache.size() > 50000)
  327. {
  328. cache.clear();
  329. }
  330. });
  331. module.exports = routes;