从项目里抽了个 Node.js rate limiter 出来,基于 Redis sorted set,支持多窗口限频

查看 28|回复 0
作者:vilic   
项目地址 https://github.com/vilic/rateman
import ms from 'ms';
import {RateLimiter, RateLimitExceededError} from 'rateman';
const rateLimiter = new RateLimiter({
  name: 'user',
  windows: [
    {span: ms('1m'), limit: 10},
    {span: ms('1h'), limit: 100},
  ],
});
try {
  await rateLimiter.attempt('[u]');
} catch (error) {
  if (error instanceof RateLimitExceededError) {
    // ...
  }
}
Express
app.use((req, _res, next) => {
  const ip = req.headers['x-forwarded-for'] || req.ip;
  void rateLimiter.attempt(ip).then(
    () => next(),
    error => next(error),
  );
});
您需要登录后才可以回帖 登录 | 立即注册

返回顶部