Skip to content

Commit

Permalink
(hopefully) add rate limit protection
Browse files Browse the repository at this point in the history
Signed-off-by: Patrick Martin <me@psm.pm>
  • Loading branch information
thonkinator committed Sep 4, 2023
1 parent d7be56c commit 6255790
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Hono, type Context } from "hono";
import type { APIUser } from "discord-api-types/v10";
import type { APIUser, RESTRateLimit } from "discord-api-types/v10";

type Bindings = {
TOKEN: string;
Expand Down Expand Up @@ -28,13 +28,17 @@ app.use("*", async (c, next) => {
});

async function api(c: Context<{ Bindings: Bindings }>, endpoint: string) {
return (
const res: RESTRateLimit = await (
await fetch(`https://discord.com/api/v10${endpoint}`, {
headers: {
Authorization: `Bot ${c.env.TOKEN}`,
},
})
).json();
if (!res.retry_after) return res;
return new Promise((resolve, reject) => {
setTimeout(() => resolve(api(c, endpoint)), res.retry_after * 1000);
});
}

async function cdn(c: Context<{ Bindings: Bindings }>, endpoint: string) {
Expand Down

0 comments on commit 6255790

Please sign in to comment.