- Next.js 16 App Router + TypeScript + Tailwind CSS 4 - Prisma/SQLite 기반 공지사항·자료실·관리자·문의/제보 - 네이버 블로그 RSS 최신 글 5개 노출 - OCI 운영 배포 스크립트 및 문서
47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
type Bucket = {
|
|
count: number;
|
|
resetAt: number;
|
|
};
|
|
|
|
const buckets = new Map<string, Bucket>();
|
|
|
|
export type RateLimitResult = {
|
|
ok: boolean;
|
|
retryAfterSeconds: number;
|
|
};
|
|
|
|
/**
|
|
* 단일 서버(OCI/VPS) 운영을 전제로 한 메모리 기반 제한입니다.
|
|
* 서버를 여러 대로 늘릴 경우 Redis/DB 기반으로 교체해야 합니다.
|
|
*/
|
|
export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult {
|
|
const now = Date.now();
|
|
const current = buckets.get(key);
|
|
|
|
if (!current || current.resetAt <= now) {
|
|
buckets.set(key, { count: 1, resetAt: now + windowMs });
|
|
return { ok: true, retryAfterSeconds: 0 };
|
|
}
|
|
|
|
if (current.count >= limit) {
|
|
return {
|
|
ok: false,
|
|
retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000)),
|
|
};
|
|
}
|
|
|
|
current.count += 1;
|
|
return { ok: true, retryAfterSeconds: 0 };
|
|
}
|
|
|
|
// 오래된 버킷이 무한히 쌓이지 않도록 가끔 정리합니다.
|
|
if (typeof setInterval !== "undefined") {
|
|
const timer = setInterval(() => {
|
|
const now = Date.now();
|
|
for (const [key, bucket] of buckets) {
|
|
if (bucket.resetAt <= now) buckets.delete(key);
|
|
}
|
|
}, 10 * 60 * 1000);
|
|
if (typeof timer === "object" && "unref" in timer) timer.unref();
|
|
}
|