mirror of
https://github.com/lukevella/rallly.git
synced 2025-08-06 01:48:32 +02:00
✨ Feedback form (#1670)
This commit is contained in:
parent
2cd5adddae
commit
1ad5f7019a
8 changed files with 216 additions and 9 deletions
44
apps/web/src/features/rate-limit/index.ts
Normal file
44
apps/web/src/features/rate-limit/index.ts
Normal file
|
@ -0,0 +1,44 @@
|
|||
"server-only";
|
||||
|
||||
import { Ratelimit } from "@upstash/ratelimit";
|
||||
import { kv } from "@vercel/kv";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { auth } from "@/next-auth";
|
||||
|
||||
import { isRateLimitEnabled } from "./constants";
|
||||
|
||||
type Unit = "ms" | "s" | "m" | "h" | "d";
|
||||
type Duration = `${number} ${Unit}` | `${number}${Unit}`;
|
||||
|
||||
async function getIPAddress() {
|
||||
return headers().get("x-forwarded-for");
|
||||
}
|
||||
|
||||
export async function rateLimit(
|
||||
name: string,
|
||||
requests: number,
|
||||
duration: Duration,
|
||||
) {
|
||||
if (!isRateLimitEnabled) {
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const identifier = session?.user?.id || (await getIPAddress());
|
||||
try {
|
||||
const ratelimit = new Ratelimit({
|
||||
redis: kv,
|
||||
limiter: Ratelimit.slidingWindow(requests, duration),
|
||||
});
|
||||
|
||||
return ratelimit.limit(`${identifier}:${name}`);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue