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.

330 lines
8.3 KiB

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