All files / lib rate-limit.ts

0% Statements 0/33
0% Branches 0/1
0% Functions 0/1
0% Lines 0/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                                                                   
import { redis } from './redis';

export type RateLimitResult = {
  allowed: boolean;
  remaining: number;
  resetIn: number;
};

export async function checkRateLimit({
  key,
  limit,
  windowSeconds,
}: {
  key: string;
  limit: number;
  windowSeconds: number;
}): Promise<RateLimitResult> {
  const fullKey = `ratelimit:${key}`;
  const count = await redis.incr(fullKey);
  if (count === 1) {
    await redis.expire(fullKey, windowSeconds);
  }
  const ttl = await redis.ttl(fullKey);
  return {
    allowed: count <= limit,
    remaining: Math.max(0, limit - count),
    resetIn: ttl < 0 ? windowSeconds : ttl,
  };
}

export async function resetRateLimit(key: string): Promise<void> {
  await redis.del(`ratelimit:${key}`);
}