animir / node-rate-limiter-flexible

Atomic counters and rate limiting tools. Limit resource access at any scale.
ISC License
3.03k stars 157 forks source link

RateLimiterRedis don't aplly params to define limiters #151

Closed brocchirodrigo closed 2 years ago

brocchirodrigo commented 2 years ago

The middleware of createClient don't initiate RaterLimiterRedis method from param "storeClient". The connection to Redis awaiting action and lost communication during execution. PS: Information in README to the feature is out of date to RedisClient.

animir commented 2 years ago

@brocchirodrigo Hey, what redis package and version do you use? Could you share a link with README you're talking about?

brocchirodrigo commented 2 years ago

Version "rate-limiter-flexible": "^2.3.6"

In "Usage" of RateLimiterRedis, the component opt don't use socket or legacyMode. I had to put these options to work and inicialize connector to redis client:

My middleware:

import { Request, Response, NextFunction } from 'express';
import { RateLimiterRedis } from 'rate-limiter-flexible';
import * as redis from 'redis';

import AppError from '@error/AppError';

export default async function rateLimiter(
  request: Request,
  response: Response,
  next: NextFunction,
): Promise<void> {
  const redisClient = redis.createClient({
    legacyMode: true,
    socket: {
      host: process.env.REDIS_HOST,
      port: Number(process.env.REDIS_PORT),
    },
  });

  await redisClient.connect();

  const rateLimiterDef = new RateLimiterRedis({
    storeClient: redisClient,
    keyPrefix: 'rate-limit',
    points: 20,
    duration: 5,
    blockDuration: 10,
  });

  try {
    await rateLimiterDef.consume(request.ip);
    return next();
  } catch (err) {
    throw new AppError('Too many requests', 429);
  }
}
animir commented 2 years ago

@brocchirodrigo What redis package version do you use?

brocchirodrigo commented 2 years ago

Sorry, I copied the wrong information in the previous comment. "redis": "^4.0.1"

animir commented 2 years ago

@brocchirodrigo We faced some issues with redis v4.x before. Please, use previous version of redis package. If you fix RateLimiterRedis to work with redis version 4, please, create a PR with changes.