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.

325 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. const minimizeRepositories = repositories => {
  170. let rList = [];
  171. repositories.forEach(repo => {
  172. rList.push(copyWithProperties(["name", "created_at", "homepage",
  173. "description", "language", "forks", "watchers",
  174. "open_issues_count", "license", "html_url"],
  175. repo));
  176. })
  177. return rList;
  178. }
  179. /**
  180. * Fetches all repositories from the API
  181. *
  182. * @param {*} user name of org/user
  183. * @param {*} orgsOrUsers either /users/ or /orgs/
  184. */
  185. const queryRepositories = async (user, orgsOrUsers) => {
  186. const cacheHit = cache.get(user + REPOS_PATH);
  187. if (cacheHit) {
  188. console.log("Repositories cache hit");
  189. return cacheHit;
  190. }
  191. try {
  192. const repos = await fetchAllWithPagination(orgsOrUsers + user + REPOS_PATH, 1, []);
  193. const minRepos = minimizeRepositories(repos);
  194. cache.put(`${user}${REPOS_PATH}`, minRepos);
  195. return minRepos;
  196. } catch (error) {
  197. console.log(error)
  198. console.log("bad things went down");
  199. }
  200. }
  201. /**
  202. * /users/name/following/followers
  203. */
  204. routes.get("/friends/:name", async (req, res)=> {
  205. try {
  206. const query = await queryFriends(req.params.name);
  207. res.json(query);
  208. } catch (error) {
  209. res.status(500).json({error: 'API error fetching friends'});
  210. }
  211. });
  212. routes.get("/org/users/:name", async (request, res) => {
  213. try {
  214. const orgMembers = await getOrganizationMembers(request.params.name);
  215. res.json(orgMembers).end();
  216. } catch (error) {
  217. res
  218. .status(500)
  219. .json({error: 'API error fetching friends'})
  220. .end();
  221. }
  222. });
  223. routes.get("/repositories/:name", async (req, res) => {
  224. try {
  225. const repos = await queryRepositories(req.params.name, API_USER_PATH);
  226. res.json(repos).end();
  227. } catch (error) {
  228. res.status(500)
  229. .json({error: 'API error fetching friends'})
  230. .end();
  231. }
  232. });
  233. routes.get("/org/repositories/:name", (request, result)=>
  234. {
  235. queryRepositories(request.params.name, API_ORGS_PATH).then(repos=>
  236. {
  237. result.json(repos)
  238. .end();
  239. }).catch(error=>
  240. {
  241. result.status(500)
  242. .json({error: 'API error fetching friends'})
  243. .end();
  244. });
  245. });
  246. routes.get('/*', (request, result) =>
  247. {
  248. var gitHubAPIURL = request.url;
  249. result.setHeader('Content-Type', 'application/json');
  250. queryGitHubAPI(gitHubAPIURL).then((data)=>
  251. {
  252. if(data.hasOwnProperty("id") || data[0].hasOwnProperty("id"))
  253. {
  254. result.write(JSON.stringify(data));
  255. }
  256. else
  257. {
  258. result.write("[]");
  259. }
  260. result.end();
  261. }).catch((error)=>
  262. {
  263. try
  264. {
  265. if(error.hasOwnProperty("id") || error[0].hasOwnProperty("id"))
  266. {
  267. result.write(JSON.stringify(error));
  268. }
  269. else
  270. {
  271. result.write("[]");
  272. }
  273. }
  274. catch(error)
  275. {
  276. result.write("[]");
  277. };
  278. result.end();
  279. });
  280. if(cache.size() > 50000)
  281. {
  282. cache.clear();
  283. }
  284. });
  285. module.exports = routes;