diff --git a/src/index.js b/src/index.js index 76be733..a4c4d9c 100644 --- a/src/index.js +++ b/src/index.js @@ -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, () => { diff --git a/src/utils/fetchServerInfo.js b/src/utils/fetchServerInfo.js index b7fe89a..37b574a 100644 --- a/src/utils/fetchServerInfo.js +++ b/src/utils/fetchServerInfo.js @@ -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"), }; }