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 cacheKey = 'rate_limit:$name:${key(request)}:$index';

  CacheStore counts = _counts();
  // the ttl is one full window, so the key is gone after its window
  await counts.add(cacheKey, 0, per);
  int 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();
}