MCPcopy Index your code
hub / github.com/triggerdotdev/trigger.dev / applyRateLimit

Function applyRateLimit

apps/proxy/src/rateLimit.ts:5–46  ·  view source on GitHub ↗
(
  request: Request,
  env: Env,
  fn: () => Promise<Response>
)

Source from the content-addressed store, hash-verified

3import { json } from "./json";
4
5export async function applyRateLimit(
6 request: Request,
7 env: Env,
8 fn: () => Promise<Response>
9): Promise<Response> {
10 const apiKey = getApiKeyFromRequest(request);
11 if (apiKey) {
12 const result = await env.API_RATE_LIMITER.limit({ key: `apikey-${apiKey.apiKey}` });
13 const { success } = result;
14 console.log(`Rate limiter`, {
15 success,
16 key: `${apiKey.apiKey.substring(0, 12)}...`,
17 });
18 if (!success) {
19 //60s in the future
20 const reset = Date.now() + 60 * 1000;
21 const secondsUntilReset = Math.max(0, (reset - new Date().getTime()) / 1000);
22
23 return json(
24 {
25 title: "Rate Limit Exceeded",
26 status: 429,
27 type: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429",
28 detail: `Rate limit exceeded. Retry in ${secondsUntilReset} seconds.`,
29 error: `Rate limit exceeded. Retry in ${secondsUntilReset} seconds.`,
30 reset,
31 },
32 {
33 status: 429,
34 headers: {
35 "x-ratelimit-reset": reset.toString(),
36 },
37 }
38 );
39 }
40 } else {
41 console.log(`Rate limiter: no API key for request`);
42 }
43
44 //call the original function
45 return fn();
46}

Callers 1

fetchFunction · 0.90

Calls 6

getApiKeyFromRequestFunction · 0.90
jsonFunction · 0.90
maxMethod · 0.80
toStringMethod · 0.80
logMethod · 0.65
limitMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…