You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
22 lines
508 B
22 lines
508 B
import { createError } from "h3";
|
|
import { getRedis } from "./redis";
|
|
|
|
export async function rateLimitOrThrow(
|
|
key: string,
|
|
limit: number,
|
|
windowSeconds: number,
|
|
): Promise<void> {
|
|
const redis = getRedis();
|
|
const n = await redis.incr(key);
|
|
if (n === 1) {
|
|
await redis.expire(key, windowSeconds);
|
|
}
|
|
if (n > limit) {
|
|
throw createError({
|
|
statusCode: 429,
|
|
data: {
|
|
error: { code: "RATE_LIMITED", message: "请求过于频繁,请稍后再试" },
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|