aboutsummaryrefslogtreecommitdiff
path: root/lib/redis.ts
blob: 17789335e57303165832b651cd199f0a1dbff414 (plain) (blame)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
import { Redis } from "ioredis";
import { RateLimiterRedis } from "rate-limiter-flexible";

const REDIS_URL: string | undefined = process.env.REDIS_URL;

let redis: Redis;
let rateLimiterRedis: RateLimiterRedis;
let rateLimitStrict: RateLimiterRedis;
let rateSuperStrict: RateLimiterRedis;

if (REDIS_URL) {
  redis = new Redis(REDIS_URL);
  redis.on("error", (err: Error) => {
    console.error("Redis error: ", err);
  });

  const opt = {
    storeClient: redis,
    keyPrefix: "rateLimit",
    points: 50,
    duration: 1,
  };

  const optStrict = {
    storeClient: redis,
    keyPrefix: "rateLimitStrict",
    points: 20,
    duration: 1,
  };

  const optSuperStrict = {
    storeClient: redis,
    keyPrefix: "rateLimitSuperStrict",
    points: 3,
    // duration 10 minutes
    duration: 10 * 60,
    blockDuration: 10 * 60,
  };

  rateLimiterRedis = new RateLimiterRedis(opt);
  rateLimitStrict = new RateLimiterRedis(optStrict);
  rateSuperStrict = new RateLimiterRedis(optSuperStrict);
} else {
  console.warn("REDIS_URL is not defined. Redis caching will be disabled.");
}

export { redis, rateLimiterRedis, rateLimitStrict, rateSuperStrict };