Skip to content

Commit

Permalink
feat add actual ratelimiting code
Browse files Browse the repository at this point in the history
  • Loading branch information
gitlimes committed May 15, 2024
1 parent cd298cc commit cd447b9
Showing 2 changed files with 39 additions and 21 deletions.
57 changes: 37 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -50,28 +50,45 @@ client.once(Events.ClientReady, (readyClient) => {
res.status(200).send(shield);
});

let stopRequestsUntil = 0;
app.get("/api/server/:invite*", async (req, res) => {
const invite = req.params.invite + req.params?.["0"];

const { compact, theme, style, logoColor } = req.query;

const serverInfo = await fetchServerInfo(invite);

if (serverInfo.error) {
return res.status(400).send(serverInfo.error);
if (
!stopRequestsUntil ||
Math.round(Date.now() / 1000) > stopRequestsUntil
) {
const invite = req.params.invite + req.params?.["0"];

const { compact, theme, style, logoColor } = req.query;

const serverInfo = await fetchServerInfo(invite);

if (serverInfo.error) {
if (serverInfo.retryAfter) {
stopRequestsUntil =
Math.round(Date.now() / 1000) + Number(serverInfo.retryAfter);
console.log(
`Pausing requests until UNIX ${stopRequestsUntil} (${new Date(
stopRequestsUntil * 1000
)})`
);
}
return res.status(400).send(serverInfo.error);
}

const shield = await generateShield({
label: serverInfo.name,
message: `${serverInfo.memberCount} members`,
compact,
theme,
style,
logoColor,
});

res.setHeader("Content-Type", "image/svg+xml");
res.status(200).send(shield);
} else {
res.status(429).send("ratelimited.");
}

const shield = await generateShield({
label: serverInfo.name,
message: `${serverInfo.memberCount} members`,
compact,
theme,
style,
logoColor,
});

res.setHeader("Content-Type", "image/svg+xml");
res.status(200).send(shield);
});

app.listen(port, () => {
3 changes: 2 additions & 1 deletion src/utils/fetchServerInfo.js
Original file line number Diff line number Diff line change
@@ -28,7 +28,8 @@ export default async function fetchServerInfo(invite) {

if (!serverFetch.ok) {
return {
error: `fetch error, potentially ratelimited?\ncode: ${serverFetch.status}`,
error: `fetch error: ${serverFetch.status}, ${serverFetch.statusText}`,
retryAfter: serverFetch.headers.get("retry-after"),
};
}

0 comments on commit cd447b9

Please sign in to comment.