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.
24 lines
666 B
24 lines
666 B
import log4js from "logger";
|
|
|
|
const logger = log4js.getLogger("APP");
|
|
|
|
type Window = { count: number; resetAt: number };
|
|
|
|
const windows = new Map<string, Window>();
|
|
|
|
export function assertUnderRateLimit(key: string, max: number, windowMs: number) {
|
|
const now = Date.now();
|
|
let w = windows.get(key);
|
|
if (!w || now > w.resetAt) {
|
|
w = { count: 0, resetAt: now + windowMs };
|
|
windows.set(key, w);
|
|
}
|
|
w.count += 1;
|
|
if (w.count > max) {
|
|
logger.warn("[RATE-LIMIT] key=%s count=%d max=%d — 请求被限流", key, w.count, max);
|
|
throw createError({
|
|
statusCode: 429,
|
|
statusMessage: "请求过于频繁,请稍后再试",
|
|
});
|
|
}
|
|
}
|
|
|