handle method
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';
// 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 {
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();
}