Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { email } from "https://esm.town/v/std/email?v=9";
let { rateLimitData } = await import("https://esm.town/v/stevekrouse/rateLimitData");
import { msDay } from "https://esm.town/v/stevekrouse/msDay";
// simple rate limiter to ensure you don't get a surprise api bill
// supports multiple keys, so you can rate limit various things
// the default limit is 1000 but you can supply your own
// the default filter is the last 24-hours, rolling, but you can supply your own
// you can an email every time someone tries to call it past the limit
// usage example: https://www.val.town/v/stevekrouse.ratedLimitedFuncEx
export function rateLimit(
key: string,
limit = 1000,
filter = (ms) => Date.now() - ms < msDay,
) {
if (!rateLimitData)
rateLimitData = {};
if (!rateLimitData[key])
rateLimitData[key] = [];
// only track today's
rateLimitData[key] = rateLimitData[key].filter(
filter,
);
rateLimitData[key].push(Date.now());
if (rateLimitData[key].length >= limit) {
// TODO: don't email so often, only do it every 10% percent chunk above the limit
return email({
text: rateLimitData[key],
subject: `${key} exceeded the rate limit`,
});
}
return true;
}
October 23, 2023