2023-10-17 18:26:49 +00:00
|
|
|
import { TRPCError } from "@calcom/trpc/server";
|
2023-06-26 19:44:58 +00:00
|
|
|
|
|
|
|
import type { RateLimitHelper } from "./rateLimit";
|
|
|
|
import { rateLimiter } from "./rateLimit";
|
|
|
|
|
|
|
|
export async function checkRateLimitAndThrowError({
|
|
|
|
rateLimitingType = "core",
|
|
|
|
identifier,
|
|
|
|
}: RateLimitHelper) {
|
|
|
|
const { remaining, reset } = await rateLimiter()({ rateLimitingType, identifier });
|
|
|
|
|
2023-10-23 20:15:43 +00:00
|
|
|
if (remaining < 1) {
|
2023-06-26 19:44:58 +00:00
|
|
|
const convertToSeconds = (ms: number) => Math.floor(ms / 1000);
|
|
|
|
const secondsToWait = convertToSeconds(reset - Date.now());
|
|
|
|
throw new TRPCError({
|
|
|
|
code: "TOO_MANY_REQUESTS",
|
|
|
|
message: `Rate limit exceeded. Try again in ${secondsToWait} seconds.`,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|