github-readme-stats/api/pin.js

90 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-09-24 20:10:06 +08:00
import { renderRepoCard } from "../src/cards/repo-card.js";
import { blacklist } from "../src/common/blacklist.js";
import {
clampValue,
CONSTANTS,
2022-09-24 19:20:52 +08:00
parseBoolean,
renderError,
} from "../src/common/utils.js";
2022-09-24 20:10:06 +08:00
import { fetchRepo } from "../src/fetchers/repo-fetcher.js";
2022-09-24 19:20:52 +08:00
import { isLocaleAvailable } from "../src/translations.js";
2020-07-10 00:53:14 +08:00
export default async (req, res) => {
const {
username,
repo,
hide_border,
title_color,
icon_color,
text_color,
bg_color,
theme,
show_owner,
cache_seconds,
locale,
border_radius,
border_color,
} = req.query;
2020-07-10 00:53:14 +08:00
res.setHeader("Content-Type", "image/svg+xml");
2020-07-10 20:42:31 +08:00
2020-08-17 16:48:17 +08:00
if (blacklist.includes(username)) {
return res.send(renderError("Something went wrong"));
}
if (locale && !isLocaleAvailable(locale)) {
return res.send(renderError("Something went wrong", "Language not found"));
}
2020-07-10 20:42:31 +08:00
try {
const repoData = await fetchRepo(username, repo);
2020-07-10 20:42:31 +08:00
2020-08-13 23:48:26 +08:00
let cacheSeconds = clampValue(
parseInt(cache_seconds || CONSTANTS.FOUR_HOURS, 10),
CONSTANTS.FOUR_HOURS,
CONSTANTS.ONE_DAY,
2020-08-13 23:48:26 +08:00
);
cacheSeconds = process.env.CACHE_SECONDS
? parseInt(process.env.CACHE_SECONDS, 10) || cacheSeconds
: cacheSeconds;
2020-08-13 23:48:26 +08:00
/*
if star count & fork count is over 1k then we are kFormating the text
and if both are zero we are not showing the stats
so we can just make the cache longer, since there is no need to frequent updates
*/
const stars = repoData.starCount;
2020-08-13 23:48:26 +08:00
const forks = repoData.forkCount;
const isBothOver1K = stars > 1000 && forks > 1000;
const isBothUnder1 = stars < 1 && forks < 1;
if (!cache_seconds && (isBothOver1K || isBothUnder1)) {
cacheSeconds = CONSTANTS.FOUR_HOURS;
}
res.setHeader(
"Cache-Control",
`max-age=${
cacheSeconds / 2
}, s-maxage=${cacheSeconds}, stale-while-revalidate=${CONSTANTS.ONE_DAY}`,
);
2020-08-13 23:48:26 +08:00
return res.send(
renderRepoCard(repoData, {
hide_border: parseBoolean(hide_border),
2020-08-13 23:48:26 +08:00
title_color,
icon_color,
text_color,
bg_color,
theme,
border_radius,
border_color,
2020-08-13 23:48:26 +08:00
show_owner: parseBoolean(show_owner),
locale: locale ? locale.toLowerCase() : null,
}),
2020-08-13 23:48:26 +08:00
);
} catch (err) {
res.setHeader("Cache-Control", `no-cache, no-store, must-revalidate`); // Don't cache error responses.
2020-08-13 23:48:26 +08:00
return res.send(renderError(err.message, err.secondaryMessage));
}
2020-07-10 00:53:14 +08:00
};