handle method

  1. @override
Future handle(
  1. IDoxRequest req
)
override

Implementation

@override
Future<dynamic> handle(IDoxRequest req) async {
  DoxRequest request = req as DoxRequest;
  int window = per.inMilliseconds;
  int now = _now().millisecondsSinceEpoch;
  int index = now ~/ window;
  String client = key(request);
  String cacheKey = 'rate_limit:$name:$client:$index';

  if (sliding) return _sliding(request, window, now, index, client);

  // the ttl is one full window, so the key is gone after its window
  CacheStore? counts = _cacheStore();
  int hits;
  if (counts == null) {
    hits = await RateLimitCounter.instance.increment(cacheKey, per);
  } else if (counts.driver is RedisDriver) {
    hits = await _countOnRedis(counts, cacheKey, per);
  } else {
    await counts.add(cacheKey, 0, per);
    hits = await counts.increment(cacheKey);
  }

  HttpHeaders headers = req.httpRequest.response.headers;
  headers.set('X-RateLimit-Limit', max);
  headers.set('X-RateLimit-Remaining', math.max(0, max - hits));
  if (hits <= max) return req;

  int waitMs = (index + 1) * window - now;
  headers.set(HttpHeaders.retryAfterHeader, (waitMs / 1000).ceil());
  throw TooManyRequestsException();
}