Compare commits
12
Commits
ranking
...
fix-ratelimit
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
429d65a52b | ||
|
|
3d8dea90e2 | ||
|
|
2efb399f33 | ||
|
|
dcde5f8205 | ||
|
|
3b3ce41ae4 | ||
|
|
e3519ceb4c | ||
|
|
c297798889 | ||
|
|
6059cb1691 | ||
|
|
cbd0e583ff | ||
|
|
6f79b495a6 | ||
|
|
014f710e12 | ||
|
|
29d3ea63f8 |
@@ -18,7 +18,9 @@ module.exports = async (req, res) => {
|
||||
} = req.query;
|
||||
let stats;
|
||||
|
||||
res.setHeader("Cache-Control", "public, max-age=1800");
|
||||
res.setHeader("Content-Type", "image/svg+xml");
|
||||
|
||||
try {
|
||||
stats = await fetchStats(username);
|
||||
} catch (err) {
|
||||
|
||||
@@ -14,6 +14,8 @@ module.exports = async (req, res) => {
|
||||
} = req.query;
|
||||
|
||||
let repoData;
|
||||
|
||||
res.setHeader("Cache-Control", "public, max-age=1800");
|
||||
res.setHeader("Content-Type", "image/svg+xml");
|
||||
|
||||
try {
|
||||
|
||||
@@ -140,15 +140,29 @@ You usually won't be able to layout the images side by side to do that you can u
|
||||
</a>
|
||||
```
|
||||
|
||||
## Deploy on your own vercel instance
|
||||
## Deploy on your own Vercel instance
|
||||
|
||||
Since Github API only allows 5k requests per hour it is possible that my `https://github-readme-stats.vercel.app/api` could hit the rate limiter thats why if you want to host it on your own vercel server then you don't have to worry about anything. click on the deploy button to get started
|
||||
|
||||
[](https://vercel.com/import/project?template=https://github.com/anuraghazra/github-readme-stats)
|
||||
|
||||
Make sure to add your own `GITHUB_TOKEN` in `Environment Variables`
|
||||
[Github Docs: Creating a github personal token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token)
|
||||
### Guide on setting up Vercel
|
||||
1. Go to [vercel.com](https://vercel.com/)
|
||||
1. Click on `Log in`
|
||||

|
||||
1. Sign in with GitHub by pressing `Continue with GitHub`
|
||||

|
||||
1. Sign into GitHub and allow access to all repositories, if prompted
|
||||
1. Fork this repo
|
||||
1. Go back to your [Vercel dashboard](https://vercel.com/dashboard)
|
||||
1. Select `Import project`
|
||||

|
||||
1. Select `Import Git Repository`
|
||||

|
||||
1. Select root and keep everything as is, just add your environment variable named GITHUB_TOKEN (as shown), which will contain a personal access token (PAT), which you can easily create [here](https://github.com/settings/tokens/new) (leave everything as is, just name it something, can be anything you want.)
|
||||

|
||||
1. Click deploy, and you're good to go. See your domains to use the API!
|
||||
|
||||
Contributions are welcomed! <3
|
||||
|
||||
Made with :heart: and javascript.
|
||||
Made with :heart: and JavaScript.
|
||||
|
||||
+18
-11
@@ -1,12 +1,10 @@
|
||||
const { request } = require("./utils");
|
||||
const retryer = require("./retryer");
|
||||
|
||||
async function fetchRepo(username, reponame) {
|
||||
if (!username || !reponame) {
|
||||
throw new Error("Invalid username or reponame");
|
||||
}
|
||||
|
||||
const res = await request({
|
||||
query: `
|
||||
const fetcher = (variables, token) => {
|
||||
return request(
|
||||
{
|
||||
query: `
|
||||
fragment RepoInfo on Repository {
|
||||
name
|
||||
stargazers {
|
||||
@@ -33,11 +31,20 @@ async function fetchRepo(username, reponame) {
|
||||
}
|
||||
}
|
||||
`,
|
||||
variables: {
|
||||
login: username,
|
||||
repo: reponame,
|
||||
variables,
|
||||
},
|
||||
});
|
||||
{
|
||||
Authorization: `bearer ${token}`,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
async function fetchRepo(username, reponame) {
|
||||
if (!username || !reponame) {
|
||||
throw new Error("Invalid username or reponame");
|
||||
}
|
||||
|
||||
let res = await retryer(fetcher, { login: username, repo: reponame });
|
||||
|
||||
const data = res.data.data;
|
||||
|
||||
|
||||
+25
-15
@@ -1,26 +1,26 @@
|
||||
const { request } = require("./utils");
|
||||
const retryer = require("./retryer");
|
||||
const calculateRank = require("./calculateRank");
|
||||
require("dotenv").config();
|
||||
|
||||
async function fetchStats(username) {
|
||||
if (!username) throw Error("Invalid username");
|
||||
|
||||
const res = await request({
|
||||
query: `
|
||||
const fetcher = (variables, token) => {
|
||||
return request(
|
||||
{
|
||||
query: `
|
||||
query userInfo($login: String!) {
|
||||
user(login: $login) {
|
||||
name
|
||||
login
|
||||
repositoriesContributedTo(first: 100, contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
|
||||
totalCount
|
||||
}
|
||||
contributionsCollection {
|
||||
totalCommitContributions
|
||||
}
|
||||
pullRequests(first: 100) {
|
||||
repositoriesContributedTo(first: 1, contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]) {
|
||||
totalCount
|
||||
}
|
||||
issues(first: 100) {
|
||||
pullRequests(first: 1) {
|
||||
totalCount
|
||||
}
|
||||
issues(first: 1) {
|
||||
totalCount
|
||||
}
|
||||
followers {
|
||||
@@ -36,9 +36,17 @@ async function fetchStats(username) {
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
variables: { login: username },
|
||||
});
|
||||
`,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
Authorization: `bearer ${token}`,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
async function fetchStats(username) {
|
||||
if (!username) throw Error("Invalid username");
|
||||
|
||||
const stats = {
|
||||
name: "",
|
||||
@@ -47,12 +55,14 @@ async function fetchStats(username) {
|
||||
totalIssues: 0,
|
||||
totalStars: 0,
|
||||
contributedTo: 0,
|
||||
rank: "C",
|
||||
rank: { level: "C", score: 0 },
|
||||
};
|
||||
|
||||
let res = await retryer(fetcher, { login: username });
|
||||
|
||||
if (res.data.errors) {
|
||||
console.log(res.data.errors);
|
||||
throw Error("Could not fetch user");
|
||||
throw Error(res.data.errors[0].message || "Could not fetch user");
|
||||
}
|
||||
|
||||
const user = res.data.data.user;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
const calculateCircleProgress = (value) => {
|
||||
let radius = 40;
|
||||
let c = Math.PI * (radius * 2);
|
||||
|
||||
if (value < 0) value = 0;
|
||||
if (value > 100) value = 100;
|
||||
|
||||
let percentage = ((100 - value) / 100) * c;
|
||||
return percentage;
|
||||
};
|
||||
|
||||
const getAnimations = ({ progress }) => {
|
||||
return `
|
||||
/* Animations */
|
||||
@keyframes scaleIn {
|
||||
from {
|
||||
transform: translate(-5px, 5px) scale(0);
|
||||
}
|
||||
to {
|
||||
transform: translate(-5px, 5px) scale(1);
|
||||
}
|
||||
}
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes rankAnimation {
|
||||
from {
|
||||
stroke-dashoffset: ${calculateCircleProgress(0)};
|
||||
}
|
||||
to {
|
||||
stroke-dashoffset: ${calculateCircleProgress(progress)};
|
||||
}
|
||||
}
|
||||
`;
|
||||
};
|
||||
|
||||
const getStyles = ({
|
||||
titleColor,
|
||||
textColor,
|
||||
iconColor,
|
||||
show_icons,
|
||||
progress,
|
||||
}) => {
|
||||
return `
|
||||
.header {
|
||||
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor};
|
||||
animation: fadeIn 0.8s ease-in-out forwards;
|
||||
}
|
||||
.stat {
|
||||
font: 600 14px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor};
|
||||
}
|
||||
.stagger {
|
||||
opacity: 0;
|
||||
animation: fadeIn 0.3s ease-in-out forwards;
|
||||
}
|
||||
.rank-text {
|
||||
font: 800 24px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor};
|
||||
animation: scaleIn 0.3s ease-in-out forwards;
|
||||
}
|
||||
|
||||
.bold { font-weight: 700 }
|
||||
.star-icon {
|
||||
font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif;
|
||||
}
|
||||
.icon {
|
||||
fill: ${iconColor};
|
||||
display: ${!!show_icons ? "block" : "none"};
|
||||
}
|
||||
|
||||
.rank-circle-rim {
|
||||
stroke: ${titleColor};
|
||||
fill: none;
|
||||
stroke-width: 6;
|
||||
opacity: 0.2;
|
||||
}
|
||||
.rank-circle {
|
||||
stroke: ${titleColor};
|
||||
stroke-dasharray: 250;
|
||||
fill: none;
|
||||
stroke-width: 6;
|
||||
stroke-linecap: round;
|
||||
opacity: 0.8;
|
||||
transform-origin: -10px 8px;
|
||||
transform: rotate(-90deg);
|
||||
animation: rankAnimation 1s forwards ease-in-out;
|
||||
}
|
||||
|
||||
${process.env.NODE_ENV === "test" ? "" : getAnimations({ progress })}
|
||||
`;
|
||||
};
|
||||
|
||||
module.exports = getStyles;
|
||||
+52
-46
@@ -1,12 +1,21 @@
|
||||
const { kFormatter, isValidHexColor } = require("../src/utils");
|
||||
const getStyles = require("./getStyles");
|
||||
|
||||
const createTextNode = ({ icon, label, value, lineHeight, id }) => {
|
||||
const createTextNode = ({ icon, label, value, id, index, lineHeight }) => {
|
||||
const classname = icon === "★" && "star-icon";
|
||||
const kValue = kFormatter(value);
|
||||
const staggerDelay = (index + 3) * 150;
|
||||
// manually calculating lineHeight based on index instead of using <tspan dy="" />
|
||||
// to fix firefox layout bug
|
||||
const lheight = lineHeight * (index + 1);
|
||||
return `
|
||||
<tspan x="25" dy="${lineHeight}" class="stat bold">
|
||||
<tspan data-testid="icon" class="icon ${classname}">${icon}</tspan> ${label}:</tspan>
|
||||
<tspan data-testid="${id}" x="155" dy="0" class="stat">${kValue}</tspan>
|
||||
<text class="stagger" style="animation-delay: ${staggerDelay}ms" x="25" y="${lheight}">
|
||||
<tspan dx="0" data-testid="icon" class="icon ${classname}">${icon}</tspan>
|
||||
<tspan dx="0" class="stat bold">
|
||||
${label}:
|
||||
</tspan>
|
||||
<tspan x="160" data-testid="${id}" class="stat">${kValue}</tspan>
|
||||
</text>
|
||||
`;
|
||||
};
|
||||
|
||||
@@ -41,47 +50,45 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
|
||||
const textColor = (isValidHexColor(text_color) && `#${text_color}`) || "#333";
|
||||
const bgColor = (isValidHexColor(bg_color) && `#${bg_color}`) || "#FFFEFE";
|
||||
|
||||
const STAT_MAP = {
|
||||
stars: createTextNode({
|
||||
const STATS = {
|
||||
stars: {
|
||||
icon: "★",
|
||||
label: "Total Stars",
|
||||
value: totalStars,
|
||||
lineHeight: lheight,
|
||||
id: "stars",
|
||||
}),
|
||||
commits: createTextNode({
|
||||
},
|
||||
commits: {
|
||||
icon: "🕗",
|
||||
label: "Total Commits",
|
||||
value: totalCommits,
|
||||
lineHeight: lheight,
|
||||
id: "commits",
|
||||
}),
|
||||
prs: createTextNode({
|
||||
},
|
||||
prs: {
|
||||
icon: "🔀",
|
||||
label: "Total PRs",
|
||||
value: totalPRs,
|
||||
lineHeight: lheight,
|
||||
id: "prs",
|
||||
}),
|
||||
issues: createTextNode({
|
||||
},
|
||||
issues: {
|
||||
icon: "ⓘ",
|
||||
label: "Total Issues",
|
||||
value: totalIssues,
|
||||
lineHeight: lheight,
|
||||
id: "issues",
|
||||
}),
|
||||
contribs: createTextNode({
|
||||
},
|
||||
contribs: {
|
||||
icon: "📕",
|
||||
label: "Contributed to",
|
||||
value: contributedTo,
|
||||
lineHeight: lheight,
|
||||
id: "contribs",
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const statItems = Object.keys(STAT_MAP)
|
||||
const statItems = Object.keys(STATS)
|
||||
.filter((key) => !hide.includes(key))
|
||||
.map((key) => STAT_MAP[key]);
|
||||
.map((key, index) =>
|
||||
// create the text nodes, and pass index so that we can calculate the line spacing
|
||||
createTextNode({ ...STATS[key], index, lineHeight: lheight })
|
||||
);
|
||||
|
||||
// Calculate the card height depending on how many items there are
|
||||
// but if rank circle is visible clamp the minimum height to `150`
|
||||
@@ -103,12 +110,12 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
|
||||
/>
|
||||
`;
|
||||
|
||||
const rankProgress = 180 + rank.score * 0.8;
|
||||
const rankCircle = hide_rank
|
||||
? ""
|
||||
: `<g data-testid="rank-circle" transform="translate(400, ${
|
||||
height / 1.85
|
||||
})">
|
||||
<circle class="rank-circle-rim" cx="-10" cy="8" r="40" />
|
||||
<circle class="rank-circle" cx="-10" cy="8" r="40" />
|
||||
<text
|
||||
x="0"
|
||||
@@ -117,44 +124,43 @@ const renderStatsCard = (stats = {}, options = { hide: [] }) => {
|
||||
dominant-baseline="central"
|
||||
text-anchor="middle"
|
||||
class="rank-text"
|
||||
transform="translate(-5, 5)"
|
||||
>
|
||||
${rank.level}
|
||||
</text>
|
||||
</g>`;
|
||||
|
||||
// re-adjust circle progressbar's value until the ranking algo is improved
|
||||
let progress = rank.score;
|
||||
if (rank.score > 86) {
|
||||
progress = (40 + rank.score) * 0.6;
|
||||
}
|
||||
if (rank.score < 40) {
|
||||
progress = 40 + rank.score;
|
||||
}
|
||||
|
||||
const styles = getStyles({
|
||||
titleColor,
|
||||
textColor,
|
||||
iconColor,
|
||||
show_icons,
|
||||
progress,
|
||||
});
|
||||
|
||||
return `
|
||||
<svg width="495" height="${height}" viewBox="0 0 495 ${height}" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<style>
|
||||
.header { font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${titleColor}; }
|
||||
.stat { font: 600 14px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor}; }
|
||||
.rank-text { font: 800 24px 'Segoe UI', Ubuntu, Sans-Serif; fill: ${textColor}; }
|
||||
.star-icon { font: 600 18px 'Segoe UI', Ubuntu, Sans-Serif; }
|
||||
.bold { font-weight: 700 }
|
||||
.icon {
|
||||
fill: ${iconColor};
|
||||
display: ${!!show_icons ? "block" : "none"};
|
||||
}
|
||||
.rank-circle {
|
||||
stroke-dashoffset: 30;
|
||||
stroke-dasharray: ${rankProgress};
|
||||
stroke: ${titleColor};
|
||||
fill: none;
|
||||
stroke-width: 6;
|
||||
stroke-linecap: round;
|
||||
opacity: 0.8;
|
||||
transform-origin: -10px 8px;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
${styles}
|
||||
</style>
|
||||
|
||||
${hide_border ? "" : border}
|
||||
|
||||
${rankCircle}
|
||||
|
||||
<text x="25" y="35" class="header">${name}'s GitHub Stats</text>
|
||||
<text y="45">
|
||||
|
||||
<svg x="0" y="45">
|
||||
${statItems.toString().replace(/\,/gm, "")}
|
||||
</text>
|
||||
</svg>
|
||||
</svg>
|
||||
`;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
const retryer = async (fetcher, variables, retries = 0) => {
|
||||
if (retries > 7) {
|
||||
throw new Error("Maximum retries exceeded");
|
||||
}
|
||||
try {
|
||||
console.log(`Trying PAT_${retries + 1}`);
|
||||
|
||||
// try to fetch with the first token since RETRIES is 0 index i'm adding +1
|
||||
let response = await fetcher(
|
||||
variables,
|
||||
process.env[`PAT_${retries + 1}`],
|
||||
retries
|
||||
);
|
||||
|
||||
// prettier-ignore
|
||||
const isRateExceeded = response.data.errors && response.data.errors[0].type === "RATE_LIMITED";
|
||||
|
||||
// if rate limit is hit increase the RETRIES and recursively call the retryer
|
||||
// with username, and current RETRIES
|
||||
if (isRateExceeded) {
|
||||
console.log(`PAT_${retries + 1} Failed`);
|
||||
retries++;
|
||||
// directly return from the function
|
||||
return retryer(fetcher, variables, retries);
|
||||
}
|
||||
|
||||
// finally return the response
|
||||
return response;
|
||||
} catch (err) {
|
||||
// prettier-ignore
|
||||
// also checking for bad credentials if any tokens gets invalidated
|
||||
const isBadCredential = err.response.data && err.response.data.message === "Bad credentials";
|
||||
|
||||
if (isBadCredential) {
|
||||
console.log(`PAT_${retries + 1} Failed`);
|
||||
retries++;
|
||||
// directly return from the function
|
||||
return retryer(fetcher, variables, retries);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = retryer;
|
||||
+9
-3
@@ -33,13 +33,13 @@ function isValidHexColor(hexColor) {
|
||||
).test(hexColor);
|
||||
}
|
||||
|
||||
function request(data) {
|
||||
function request(data, headers) {
|
||||
return new Promise((resolve, reject) => {
|
||||
axios({
|
||||
url: "https://api.github.com/graphql",
|
||||
method: "post",
|
||||
headers: {
|
||||
Authorization: `bearer ${process.env.GITHUB_TOKEN}`,
|
||||
...headers,
|
||||
},
|
||||
data,
|
||||
})
|
||||
@@ -48,4 +48,10 @@ function request(data) {
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { renderError, kFormatter, encodeHTML, isValidHexColor, request };
|
||||
module.exports = {
|
||||
renderError,
|
||||
kFormatter,
|
||||
encodeHTML,
|
||||
isValidHexColor,
|
||||
request,
|
||||
};
|
||||
|
||||
@@ -74,7 +74,7 @@ describe("Test fetchStats", () => {
|
||||
mock.onPost("https://api.github.com/graphql").reply(200, error);
|
||||
|
||||
await expect(fetchStats("anuraghazra")).rejects.toThrow(
|
||||
"Could not fetch user"
|
||||
"Could not resolve to a User with the login of 'noname'."
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ describe("Test renderStatsCard", () => {
|
||||
totalIssues: 300,
|
||||
totalPRs: 400,
|
||||
contributedTo: 500,
|
||||
rank: { level: "A+", score: 100 },
|
||||
rank: { level: "A+", score: 40 },
|
||||
};
|
||||
|
||||
it("should render correctly", () => {
|
||||
@@ -66,7 +66,8 @@ describe("Test renderStatsCard", () => {
|
||||
document.body.innerHTML = renderStatsCard(stats);
|
||||
|
||||
const styleTag = document.querySelector("style");
|
||||
const stylesObject = cssToObject(styleTag.innerHTML);
|
||||
console.log(styleTag.textContent);
|
||||
const stylesObject = cssToObject(styleTag.textContent);
|
||||
|
||||
const headerClassStyles = stylesObject[".header"];
|
||||
const statClassStyles = stylesObject[".stat"];
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
require("@testing-library/jest-dom");
|
||||
const retryer = require("../src/retryer");
|
||||
|
||||
const fetcher = jest.fn((variables, token) => {
|
||||
console.log(variables, token);
|
||||
return new Promise((res, rej) => res({ data: "ok" }));
|
||||
});
|
||||
|
||||
const fetcherFail = jest.fn(() => {
|
||||
return new Promise((res, rej) =>
|
||||
res({ data: { errors: [{ type: "RATE_LIMITED" }] } })
|
||||
);
|
||||
});
|
||||
|
||||
const fetcherFailOnSecondTry = jest.fn((_vars, _token, retries) => {
|
||||
return new Promise((res, rej) => {
|
||||
// faking rate limit
|
||||
if (retries < 1) {
|
||||
return res({ data: { errors: [{ type: "RATE_LIMITED" }] } });
|
||||
}
|
||||
return res({ data: "ok" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test Retryer", () => {
|
||||
it("retryer should return value and have zero retries on first try", async () => {
|
||||
let res = await retryer(fetcher, {});
|
||||
|
||||
expect(fetcher).toBeCalledTimes(1);
|
||||
expect(res).toStrictEqual({ data: "ok" });
|
||||
});
|
||||
|
||||
it("retryer should return value and have 2 retries", async () => {
|
||||
let res = await retryer(fetcherFailOnSecondTry, {});
|
||||
|
||||
expect(fetcherFailOnSecondTry).toBeCalledTimes(2);
|
||||
expect(res).toStrictEqual({ data: "ok" });
|
||||
});
|
||||
|
||||
it("retryer should throw error if maximum retries reached", async () => {
|
||||
let res;
|
||||
|
||||
try {
|
||||
res = await retryer(fetcherFail, {});
|
||||
} catch (err) {
|
||||
expect(fetcherFail).toBeCalledTimes(8);
|
||||
expect(err.message).toBe("Maximum retries exceeded");
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user