40 lines
815 B
TypeScript
40 lines
815 B
TypeScript
import "server-only";
|
|
|
|
import { getRedisClient } from "@/lib/redis";
|
|
import { enforceFixedWindowRateLimit } from "@/lib/share/rate-limit-core";
|
|
|
|
const FIXED_WINDOW_SCRIPT = `
|
|
local count = redis.call("INCR", KEYS[1])
|
|
if count == 1 then
|
|
redis.call("EXPIRE", KEYS[1], ARGV[1])
|
|
end
|
|
return count
|
|
`;
|
|
|
|
export async function enforceShareRateLimit({
|
|
key,
|
|
limit,
|
|
windowSeconds,
|
|
}: {
|
|
key: string;
|
|
limit: number;
|
|
windowSeconds: number;
|
|
}) {
|
|
return enforceFixedWindowRateLimit({
|
|
key,
|
|
limit,
|
|
windowSeconds,
|
|
increment: async (redisKey, expiresInSeconds) => {
|
|
const redis = await getRedisClient();
|
|
return Number(
|
|
await redis.send("EVAL", [
|
|
FIXED_WINDOW_SCRIPT,
|
|
"1",
|
|
redisKey,
|
|
String(expiresInSeconds),
|
|
]),
|
|
);
|
|
},
|
|
});
|
|
}
|