leonardohipolito/laravel-http-client-rate-limiter-middleware

This is my package laravel-http-client-rate-limiter-middleware

0.0.3 2023-09-05 16:55 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

A rate limiter middleware for Laravel Http Client. Here's what you need to know:

  • Specify a maximum amount of requests per minute or per second
  • When the limit is reached, the process will sleep until the request can be made
  • Implement your own driver to persist the rate limiter's request store. This is necessary if the rate limiter needs to work across separate processes, the package ships with an InMemoryStore.

Installation

You can install the package via composer:

composer require leonardohipolito/laravel-http-client-rate-limiter-middleware

Usage

Laravel 9

use GuzzleHttp\Middleware;
use \LeonardoHipolito\LaravelHttpClientRateLimiterMiddleware\RateLimiterMiddleware;
use \LeonardoHipolito\LaravelHttpClientRateLimiterMiddleware\CacheStore;
Http::macro(
    'jsonPlaceholder',
    fn () => Http::baseUrl('https://jsonplaceholder.typicode.com')
        ->withMiddleware(Middleware::mapRequest(RateLimiterMiddleware::perMinute(60, new CacheStore('jsonplaceholder-rate-limit'))))
        ->acceptJson()
        ->asJson()
);

Laravel 10

use \LeonardoHipolito\LaravelHttpClientRateLimiterMiddleware\RateLimiterMiddleware;
use \LeonardoHipolito\LaravelHttpClientRateLimiterMiddleware\CacheStore;
Http::macro(
    'jsonPlaceholder',
    fn () => Http::baseUrl('https://jsonplaceholder.typicode.com')
        ->withRequestMiddleware(RateLimiterMiddleware::perMinute(60, new CacheStore('jsonplaceholder-rate-limit')
        ->acceptJson()
        ->asJson()
);

You can create a rate limiter to limit per second or per minute.

use \LeonardoHipolito\LaravelHttpClientRateLimiterMiddleware\RateLimiterMiddleware;

RateLimiterMiddleware::perSecond(5);
RateLimiterMiddleware::perMinute(60);

Custom stores

By default, the rate limiter works in Cache. This means that if you have a second PHP process but you can create your own store.

use \LeonardoHipolito\LaravelHttpClientRateLimiterMiddleware\RateLimiterMiddleware;
use MyApp\RateLimiterStore;
use \LeonardoHipolito\LaravelHttpClientRateLimiterMiddleware\RateLimit;

RateLimiterMiddleware::perSecond(3, new RateLimiterStore());

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.