From 5f84b594a3847a9efe881148c2987edbcd02286f Mon Sep 17 00:00:00 2001 From: anuraghazra Date: Thu, 9 Jul 2020 22:23:14 +0530 Subject: [PATCH] feat: added pins! --- api/pin.js | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 api/pin.js diff --git a/api/pin.js b/api/pin.js new file mode 100644 index 00000000..c3c4d938 --- /dev/null +++ b/api/pin.js @@ -0,0 +1,111 @@ +const axios = require("axios"); +require("dotenv").config(); + +async function fetchRepo(username, reponame) { + const res = await axios({ + url: "https://api.github.com/graphql", + method: "post", + headers: { + Authorization: `bearer ${process.env.GITHUB_TOKEN}`, + }, + data: { + query: ` + query getRepo($login: String!, $repo: String!) { + user(login: $login) { + repository(name: $repo) { + name + stargazers { + totalCount + } + description + primaryLanguage { + color + id + name + } + forkCount + } + } + organization(login: $login) { + repository(name: $repo) { + name + stargazers { + totalCount + } + description + primaryLanguage { + color + id + name + } + forkCount + } + } + } + `, + variables: { + login: username, + repo: reponame, + }, + }, + }); + + if (res.data.error && res.data.error.type !== "NOT_FOUND") return {}; + if (!res.data.data.organization && res.data.data.user) + return res.data.data.user.repository; + + const isOrg = res.data.data.organization && !res.data.data.user; + if (isOrg) return res.data.data.organization.repository; + + return res.data.data.user.repository; +} + +const renderRepoCard = (repo) => { + const { name, description, primaryLanguage, stargazers, forkCount } = repo; + const height = 120; + return ` + + + + + + + + ${name} + ${description.slice( + 0, + 60 + )}.. + + + + + + + + + + + ${primaryLanguage.name} + ${stargazers.totalCount} + ${forkCount} + + `; +}; + +module.exports = async (req, res) => { + const username = req.query.username; + const repo = req.query.repo; + + const repoData = await fetchRepo(username, repo); + + res.setHeader("Content-Type", "image/svg+xml"); + res.send(renderRepoCard(repoData)); +};