Skip to content

Commit

Permalink
Merge pull request #29 from cslant/feat/Create-ratelimit-for-API-#28
Browse files Browse the repository at this point in the history
Feat/create ratelimit for api #28
  • Loading branch information
tanhongit authored Dec 10, 2024
2 parents 749c123 + e1c656b commit 5bb564f
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 4 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@
"extra": {
"laravel": {
"providers": [
"CSlant\\Blog\\Api\\Providers\\BlogApiServiceProvider"
"CSlant\\Blog\\Api\\Providers\\BlogApiServiceProvider",
"CSlant\\Blog\\Api\\Providers\\RouteServiceProvider"
]
}
},
Expand Down
4 changes: 1 addition & 3 deletions config/blog-api.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
<?php

$routePrefix = env('BLOG_API_ROUTE_PREFIX', 'api');

return [
'defaults' => [
/* Set route prefix for the blog API */
'route_prefix' => $routePrefix,
'route_prefix' => env('BLOG_API_ROUTE_PREFIX', 'api'),
],
];
3 changes: 3 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,6 @@ parameters:

- message: '#Call to an undefined static method CSlant\\Blog\\Api\\Http\\Resources\\ListPostResource::collection\(\).#'
path: src/Http/Controllers/PostController.php

- message: '#Cannot cast mixed to string#'
path: '*'
32 changes: 32 additions & 0 deletions src/Providers/RouteServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace CSlant\Blog\ApiPackage\Providers;

use CSlant\Blog\Core\Models\User;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

class RouteServiceProvider extends ServiceProvider
{
/**
* Move base routes to a service provider to make sure all filters & actions can hook to base routes
*/
public function boot(): void
{
// add rate limit for api
$this->configureRateLimiting();
}

protected function configureRateLimiting(): void
{
RateLimiter::for((string) config('blog-api.defaults.route_prefix'), function (Request $request) {
/** @var null|User $user */
$user = $request->user();
$identifier = $user ? $user->id : $request->ip();

return Limit::perMinute(40)->by($identifier);
});
}
}

0 comments on commit 5bb564f

Please sign in to comment.