Compare commits

..
Author SHA1 Message Date
anuraghazra 12fd842fce fix: description trimming & htmlEncode 2020-07-11 14:17:51 +05:30
Anurag Hazra 137a9f2038 Merge pull request #19 from omidnikrah/patch-1
Use destructuring query assignment
2020-07-10 22:47:32 +05:30
Omid Nikrah 9083ae3e49 Use destructuring props assignment 2020-07-10 21:35:14 +04:30
Anurag Hazra 43c49de37f Merge pull request #17 from anuraghazra/error-handling
feat: added better error handling
2020-07-10 18:21:52 +05:30
anuraghazra 4292212b30 feat: added better error handling 2020-07-10 18:12:31 +05:30
anuraghazra 6f6a7f2763 docs: remove bold 2020-07-10 16:21:59 +05:30
anuraghazra a27d977c7d fix: conflict 2020-07-10 16:21:02 +05:30
anuraghazra 86594ee1b8 docs: added credit notice 2020-07-10 16:19:52 +05:30
Anurag Hazra 8d982d59c6 Merge pull request #16 from nombrekeff/patch-1
docs: Some little grammar fixes and improvements.
2020-07-10 16:18:04 +05:30
Manolo Edge 2f91bd5222 Some little grammar fixes and improvements.
Just a little something, hope it helps :)
2020-07-10 12:45:03 +02:00
4 changed files with 110 additions and 122 deletions
+21 -67
View File
@@ -1,7 +1,10 @@
const axios = require("axios");
const { renderError, kFormatter } = require("../utils");
require("dotenv").config();
async function fetchStats(username) {
if (!username) throw Error("Invalid username");
const res = await axios({
url: "https://api.github.com/graphql",
method: "post",
@@ -17,7 +20,7 @@ async function fetchStats(username) {
totalCount
}
contributionsCollection {
contributionYears
totalCommitContributions
}
pullRequests(first: 100) {
totalCount
@@ -49,65 +52,17 @@ async function fetchStats(username) {
totalStars: 0,
contributedTo: 0,
};
if (res.data.error) return stats;
if (res.data.errors) {
console.log(res.data.errors);
throw Error("Could not fetch user");
}
const user = res.data.data.user;
// FETCH ALL COMMITS
let commitPromises = user.contributionsCollection.contributionYears.map(
async (year) => {
// Don't fetch contributions older than 2008 (Perf optimization)
if (year < 2008) {
return {
user: { contributionsCollection: { totalCommitContributions: 0 } },
};
}
const currentDate = new Date();
currentDate.setFullYear(year, 0, 0);
const res = await axios({
url: "https://api.github.com/graphql",
method: "post",
headers: {
Authorization: `bearer ${process.env.GITHUB_TOKEN}`,
},
data: {
query: `
query userInfo($login: String!, $from: DateTime!) {
user(login: $login) {
contributionsCollection(from: $from) {
totalCommitContributions
}
}
}
`,
variables: {
login: username,
from: currentDate.toISOString(),
},
},
});
console.log(
currentDate.toDateString(),
res.data.data.user.contributionsCollection.totalCommitContributions
);
return res.data.data;
}
);
const allCommits = await Promise.all(commitPromises);
const totalCommits = allCommits.reduce((preYear, currYear) => {
return (
preYear + currYear.user.contributionsCollection.totalCommitContributions
);
}, 0);
stats.name = user.name;
stats.totalIssues = user.issues.totalCount;
stats.totalCommits = totalCommits;
stats.totalCommits = user.contributionsCollection.totalCommitContributions;
stats.totalPRs = user.pullRequests.totalCount;
stats.contributedTo = user.repositoriesContributedTo.totalCount;
@@ -119,12 +74,11 @@ async function fetchStats(username) {
}
const createTextNode = (icon, label, value, lheight) => {
const classname = icon === "★" && "star-icon";
return `
<tspan x="25" dy="${lheight}" class="stat bold">
<tspan class="icon ${
icon === "★" && "star-icon"
}" fill="#4C71F2">${icon}</tspan> ${label}:</tspan>
<tspan x="155" dy="0" class="stat">${value}</tspan>
<tspan class="icon ${classname}" fill="#4C71F2">${icon}</tspan> ${label}:</tspan>
<tspan x="155" dy="0" class="stat">${kFormatter(value)}</tspan>
`;
};
@@ -181,16 +135,16 @@ const renderSVG = (stats, options) => {
};
module.exports = async (req, res) => {
const username = req.query.username;
const hide = req.query.hide;
const hide_border = req.query.hide_border;
const show_icons = req.query.show_icons;
const line_height = req.query.line_height;
const { username, hide, hide_border, show_icons, line_height } = req.query;
let stats;
const stats = await fetchStats(username);
res.setHeader('Cache-Control', 'public, max-age=300');
res.setHeader("Content-Type", "image/svg+xml");
try {
stats = await fetchStats(username);
} catch (err) {
return res.send(renderError(err.message));
}
res.send(
renderSVG(stats, {
hide: JSON.parse(hide || "[]"),
+51 -45
View File
@@ -1,12 +1,7 @@
const axios = require("axios");
const { renderError, kFormatter, encodeHTML } = require("../utils");
require("dotenv").config();
function kFormatter(num) {
return Math.abs(num) > 999
? Math.sign(num) * (Math.abs(num) / 1000).toFixed(1) + "k"
: Math.sign(num) * Math.abs(num);
}
async function fetchRepo(username, reponame) {
const res = await axios({
url: "https://api.github.com/graphql",
@@ -16,35 +11,28 @@ async function fetchRepo(username, reponame) {
},
data: {
query: `
fragment RepoInfo on Repository {
name
stargazers {
totalCount
}
description
primaryLanguage {
color
id
name
}
forkCount
}
query getRepo($login: String!, $repo: String!) {
user(login: $login) {
repository(name: $repo) {
name
stargazers {
totalCount
}
description
primaryLanguage {
color
id
name
}
forkCount
...RepoInfo
}
}
organization(login: $login) {
repository(name: $repo) {
name
stargazers {
totalCount
}
description
primaryLanguage {
color
id
name
}
forkCount
...RepoInfo
}
}
}
@@ -56,23 +44,39 @@ async function fetchRepo(username, 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 data = res.data.data;
const isOrg = res.data.data.organization && !res.data.data.user;
if (isOrg) return res.data.data.organization.repository;
if (!data.user && !data.organization) {
throw new Error("Not found");
}
return res.data.data.user.repository;
if (data.organization === null && data.user) {
if (!data.user.repository) {
throw new Error("User Repository Not found");
}
return data.user.repository;
}
if (data.user === null && data.organization) {
if (!data.organization.repository) {
throw new Error("Organization Repository Not found");
}
return data.organization.repository;
}
}
const renderRepoCard = (repo) => {
const { name, description, primaryLanguage, stargazers, forkCount } = repo;
const height = 120;
const shiftText = primaryLanguage.name.length > 15 ? 0 : 30;
let desc = description || "No description provided";
if (desc.length > 55) {
desc = `${description.slice(0, 55)}..`;
}
return `
<svg width="400" height="${height}" viewBox="0 0 400 ${height}" fill="none" xmlns="http://www.w3.org/2000/svg">
<svg width="400" height="${height}" viewBox="0 0 400 ${height}" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
.header { font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; fill: #2F80ED }
.stat { font: 600 14px 'Segoe UI', Ubuntu, Sans-Serif; fill: #333 }
@@ -87,11 +91,8 @@ const renderRepoCard = (repo) => {
</svg>
<text x="50" y="38" class="header">${name}</text>
<text class="description" x="25" y="70">${
description ? description.slice(0, 60) : "No description provided"
}..</text>
<text class="description" x="25" y="70">${encodeHTML(desc)}</text>
<g transform="translate(30, 100)">
<circle cx="0" cy="-5" r="6" fill="${primaryLanguage.color}" />
<text class="gray" x="15">${primaryLanguage.name}</text>
@@ -115,12 +116,17 @@ const renderRepoCard = (repo) => {
};
module.exports = async (req, res) => {
const username = req.query.username;
const repo = req.query.repo;
const { username, repo } = req.query;
const repoData = await fetchRepo(username, repo);
res.setHeader('Cache-Control', 'public, max-age=300');
let repoData;
res.setHeader("Content-Type", "image/svg+xml");
try {
repoData = await fetchRepo(username, repo);
} catch (err) {
console.log(err);
return res.send(renderError(err.message));
}
res.send(renderRepoCard(repoData));
};
+10 -10
View File
@@ -1,6 +1,6 @@
## Github Readme stats
Get dynamically generated github stats on your readmes!
Get dynamically generated GitHub stats on your readmes!
# Features
@@ -9,17 +9,17 @@ Get dynamically generated github stats on your readmes!
# Github Stats Card
Copy paste this into your markdown content and thats it. simple!
Copy paste this into your markdown content, and that's it. Simple!
change the `?username=` value to your GitHubs's username
```md
![Anurag's github stats](https://github-readme-stats.vercel.app/api?username=anuraghazra)
[![Anurag's github stats](https://github-readme-stats.vercel.app/api?username=anuraghazra)](https://github.com/anuraghazra/github-readme-stats)
```
### Hiding certain stats
### Hiding individual stats
To hide any specific stats you can pass a query parameter `?hide=` with an array of items you wanna hide.
To hide any specific stats, you can pass a query parameter `?hide=` with an array of items, you wanna hide.
> Options: `&hide=["stars","prs","issues","contribs"]`
@@ -29,7 +29,7 @@ To hide any specific stats you can pass a query parameter `?hide=` with an array
### Showing icons
To enable icons you can pass `show_icons=true` in the query param like so
To enable icons, you can pass `show_icons=true` in the query param like so
```md
![Anurag's github stats](https://github-readme-stats.vercel.app/api?username=anuraghazra&show_icons=true)
@@ -56,13 +56,13 @@ Other options:
# Github Extra Pins
Github extra pins allows you to pin more than 6 repositories in your profile by using github readme profile.
Github extra pins allow you to pin more than 6 repositories in your profile using a GitHub readme profile.
Yey! you are no longer limited to 6 pinned repos
Yey! you are no longer limited to 6 pinned repositories.
### Usage
Copy paste this code into your readme and change the links.
Copy-paste this code into your readme and change the links.
Endpoint: `api/pin?username=anuraghazra&repo=github-readme-stats`
@@ -76,7 +76,7 @@ Endpoint: `api/pin?username=anuraghazra&repo=github-readme-stats`
### Quick Tip (Align The Repo Cards)
Normally you won't be able to layout the images side by side to do that you can use this approach
You usually won't be able to layout the images side by side to do that you can use this approach
```md
<a href="https://github.com/anuraghazra/github-readme-stats">
+28
View File
@@ -0,0 +1,28 @@
const renderError = (message) => {
return `
<svg width="495" height="100" viewBox="0 0 495 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
.text { font: 600 16px 'Segoe UI', Ubuntu, Sans-Serif; fill: #2F80ED }
.small { font: 600 12px 'Segoe UI', Ubuntu, Sans-Serif; fill: #252525 }
</style>
<rect x="0.5" y="0.5" width="494" height="99%" rx="4.5" fill="#FFFEFE" stroke="#E4E2E2"/>
<text x="25" y="45" class="text">Something went wrong! file an issue at https://git.io/JJmN9</text>
<text x="25" y="65" class="text small">${message}</text>
</svg>
`;
};
// https://stackoverflow.com/a/48073476/10629172
function encodeHTML(str) {
return str.replace(/[\u00A0-\u9999<>&](?!#)/gim, function (i) {
return "&#" + i.charCodeAt(0) + ";";
});
}
function kFormatter(num) {
return Math.abs(num) > 999
? Math.sign(num) * (Math.abs(num) / 1000).toFixed(1) + "k"
: Math.sign(num) * Math.abs(num);
}
module.exports = { renderError, kFormatter, encodeHTML };