Skip to content

Commit a3dedfb

Browse files
Add rate limiting feature to DiscoverDocumentation component
1 parent caf3326 commit a3dedfb

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

app/Livewire/DiscoverDocumentation.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,15 @@
66

77
use App\Enums\Framework;
88
use App\Models\DocumentationLink;
9+
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
10+
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
911
use Illuminate\Support\Facades\Session;
1012
use Livewire\Component;
1113

1214
final class DiscoverDocumentation extends Component
1315
{
16+
use WithRateLimiting;
17+
1418
public Framework $selectedFramework = Framework::Laravel;
1519

1620
public ?DocumentationLink $link = null;
@@ -19,6 +23,10 @@ final class DiscoverDocumentation extends Component
1923

2024
public int $highScore = 0;
2125

26+
public bool $rateLimitExceeded = false;
27+
28+
public int $secondsUntilAvailable = 0;
29+
2230
protected $listeners = [
2331
'framework-switched' => 'handleFrameworkSwitch',
2432
];
@@ -32,6 +40,10 @@ public function mount(): void
3240

3341
public function getRandomLink(): void
3442
{
43+
if (! $this->checkRateLimit()) {
44+
return;
45+
}
46+
3547
$this->link = DocumentationLink::query()
3648
->where('framework', $this->selectedFramework)
3749
->inRandomOrder()
@@ -61,6 +73,21 @@ public function render()
6173
return view('livewire.discover-documentation');
6274
}
6375

76+
private function checkRateLimit(): bool
77+
{
78+
try {
79+
$this->rateLimit(3, 5);
80+
$this->rateLimitExceeded = false;
81+
82+
return true;
83+
} catch (TooManyRequestsException $tooManyRequestsException) {
84+
$this->rateLimitExceeded = true;
85+
$this->secondsUntilAvailable = $tooManyRequestsException->secondsUntilAvailable;
86+
87+
return false;
88+
}
89+
}
90+
6491
private function loadFrameworkStats(): void
6592
{
6693
$frameworkKey = $this->selectedFramework->value;

resources/views/livewire/discover-documentation.blade.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,17 @@ class="inline-block flex-1 py-[16px] px-4 bg-gradient-to-r from-[{{ $selectedFra
4040
Discover
4141
</button>
4242
</div>
43+
44+
@if ($rateLimitExceeded)
45+
<div class="w-full text-center">
46+
<p class="text-[0.65rem] text-red-400">
47+
Please wait <span
48+
class="text-[{{ $selectedFramework->color() }}]">{{ $secondsUntilAvailable }}</span>
49+
seconds before
50+
discovering another one.
51+
</p>
52+
</div>
53+
@endif
4354
</div>
4455
</div>
4556

0 commit comments

Comments
 (0)