Files
calendar/packages/lib/checkRateLimitAndThrowError.ts
T
ebca5c6409 fix: use 'success' value for better accuracy (#14624)
* fix: use 'success' value for better accuracy

* add success to test

---------

Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2024-04-17 14:01:13 +00:00

26 lines
780 B
TypeScript

import { TRPCError } from "@calcom/trpc/server";
import type { RateLimitHelper } from "./rateLimit";
import { rateLimiter } from "./rateLimit";
export async function checkRateLimitAndThrowError({
rateLimitingType = "core",
identifier,
onRateLimiterResponse,
opts,
}: RateLimitHelper) {
const response = await rateLimiter()({ rateLimitingType, identifier, opts });
const { success, reset } = response;
if (onRateLimiterResponse) onRateLimiterResponse(response);
if (!success) {
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.`,
});
}
}