github-readme-stats/api/index.js

104 lines
2.6 KiB
JavaScript
Raw Normal View History

2022-09-24 20:10:06 +08:00
import { renderStatsCard } from "../src/cards/stats-card.js";
import { blacklist } from "../src/common/blacklist.js";
import {
clampValue,
CONSTANTS,
2022-09-24 19:20:52 +08:00
parseArray,
parseBoolean,
renderError,
} from "../src/common/utils.js";
2022-09-24 20:10:06 +08:00
import { fetchStats } from "../src/fetchers/stats-fetcher.js";
2022-09-24 19:20:52 +08:00
import { isLocaleAvailable } from "../src/translations.js";
export default async (req, res) => {
const {
username,
hide,
2020-07-18 01:31:16 +08:00
hide_title,
hide_border,
card_width,
2020-07-13 22:11:47 +08:00
hide_rank,
show_icons,
count_private,
include_all_commits,
line_height,
title_color,
ring_color,
icon_color,
text_color,
text_bold,
bg_color,
theme,
cache_seconds,
exclude_repo,
custom_title,
locale,
disable_animations,
border_radius,
number_format,
border_color,
rank_icon,
} = req.query;
2020-07-09 18:33:41 +08:00
res.setHeader("Content-Type", "image/svg+xml");
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 stats = await fetchStats(
username,
parseBoolean(count_private),
parseBoolean(include_all_commits),
parseArray(exclude_repo),
);
2020-07-10 20:42:31 +08:00
2020-08-13 23:48:26 +08:00
const cacheSeconds = clampValue(
parseInt(cache_seconds || CONSTANTS.FOUR_HOURS, 10),
CONSTANTS.FOUR_HOURS,
CONSTANTS.ONE_DAY,
2020-08-13 23:48:26 +08:00
);
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(
renderStatsCard(stats, {
hide: parseArray(hide),
show_icons: parseBoolean(show_icons),
hide_title: parseBoolean(hide_title),
hide_border: parseBoolean(hide_border),
card_width: parseInt(card_width, 10),
2020-08-13 23:48:26 +08:00
hide_rank: parseBoolean(hide_rank),
include_all_commits: parseBoolean(include_all_commits),
line_height,
title_color,
ring_color,
2020-08-13 23:48:26 +08:00
icon_color,
text_color,
text_bold: parseBoolean(text_bold),
2020-08-13 23:48:26 +08:00
bg_color,
theme,
custom_title,
border_radius,
border_color,
number_format,
locale: locale ? locale.toLowerCase() : null,
disable_animations: parseBoolean(disable_animations),
rank_icon,
}),
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-09 18:33:41 +08:00
};