rateLimitInterceptor static method

Interceptor rateLimitInterceptor({
  1. int maxRequestsPerSecond = 10,
})

Creates a rate limiting interceptor

maxRequestsPerSecond - Maximum requests per second

Implementation

static Interceptor rateLimitInterceptor({int maxRequestsPerSecond = 10}) {
  final requests = <DateTime>[];

  return InterceptorsWrapper(
    onRequest: (options, handler) async {
      final now = DateTime.now();

      // Remove requests older than 1 second
      requests.removeWhere((time) => now.difference(time).inSeconds >= 1);

      if (requests.length >= maxRequestsPerSecond) {
        final oldestRequest = requests.first;
        final waitTime = Duration(seconds: 1) - now.difference(oldestRequest);
        if (waitTime.inMilliseconds > 0) {
          print(
            '⏳ [Google Maps API] Rate limiting: waiting ${waitTime.inMilliseconds}ms',
          );
          await Future.delayed(waitTime);
        }
      }

      requests.add(now);
      handler.next(options);
    },
  );
}