cal/packages/lib/rateLimit.ts
Lucas Smith 2317473545
feat(web): improve session retrieval performance (#7584)
* feat(web): improve session retrieval performance

Switch to using `getServerSession` which avoids a HTTP round trip to retrieve session details.

Additionally, migrate deprecated `app/lib/auth` calls to to `@calcom/lib` package.

* fix: update failing test and lint

* Consolidates auth code in features

* Update yarn.lock

* Update packages/trpc/server/createContext.ts

* Oopsie

---------

Co-authored-by: zomars <zomars@me.com>
2023-03-10 23:45:24 +00:00

28 lines
806 B
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
import cache from "memory-cache";
import { ErrorCode } from "@calcom/features/auth/lib/ErrorCode";
const rateLimit = (options: { intervalInMs: number }) => {
return {
check: (requestLimit: number, uniqueIdentifier: string) => {
const count = cache.get(uniqueIdentifier) || [0];
if (count[0] === 0) {
cache.put(uniqueIdentifier, count, options.intervalInMs);
}
count[0] += 1;
const currentUsage = count[0];
const isRateLimited = currentUsage >= requestLimit;
if (isRateLimited) {
throw new Error(ErrorCode.RateLimitExceeded);
}
return { isRateLimited, requestLimit, remaining: isRateLimited ? 0 : requestLimit - currentUsage };
},
};
};
export default rateLimit;