Skip to content

Commit 396cba6

Browse files
committed
feat: Implement rate limiting functionality
1 parent 9380a50 commit 396cba6

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

src/lib/rate-limit.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import consola from "consola"
2+
3+
import type { State } from "./state"
4+
5+
import { HTTPError } from "./http-error"
6+
7+
export function checkRateLimit(state: State) {
8+
if (state.rateLimitSeconds === undefined) return
9+
10+
const now = Date.now()
11+
12+
if (!state.lastRequestTimestamp) {
13+
state.lastRequestTimestamp = now
14+
return
15+
}
16+
17+
const elapsedSeconds = (now - state.lastRequestTimestamp) / 1000
18+
19+
if (elapsedSeconds > state.rateLimitSeconds) {
20+
state.lastRequestTimestamp = now
21+
return
22+
}
23+
24+
const waitTimeSeconds = Math.round(state.rateLimitSeconds - elapsedSeconds)
25+
consola.warn(
26+
`Rate limit exceeded. Need to wait ${waitTimeSeconds} more seconds.`,
27+
)
28+
29+
throw new HTTPError("Rate limit exceeded", Response.json({ status: 429 }))
30+
}

0 commit comments

Comments
 (0)