aboutsummaryrefslogtreecommitdiff
path: root/lib/redis.js
blob: 9522e4c9f7cfff4cd068768edfe945facc3d8751 (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 = process.env.REDIS_URL;

let redis;
let rateLimiterRedis;
let rateLimitStrict;
let rateSuperStrict;

if (REDIS_URL) {
  redis = new Redis(REDIS_URL);
  redis.on("error", (err) => {
    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 };