Skip to content

Commit

Permalink
feat: record page view for names (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
djaiss authored Feb 19, 2024
1 parent a970c40 commit 4181d58
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
3 changes: 3 additions & 0 deletions app/Http/Controllers/NameController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use App\Http\ViewModels\Names\NameViewModel;
use App\Http\ViewModels\User\ListViewModel;
use App\Http\ViewModels\User\UserViewModel;
use App\Jobs\IncrementPageViewForName;
use App\Models\Name;
use App\Services\ToggleNameToNameList;
use Illuminate\Contracts\View\View;
Expand Down Expand Up @@ -65,6 +66,8 @@ public function show(Request $request): View
$note = $requestedName->getNoteForUser();
}

IncrementPageViewForName::dispatch($requestedName->id);

return view('names.show', [
'name' => $name,
'popularity' => $popularity,
Expand Down
31 changes: 31 additions & 0 deletions app/Jobs/IncrementPageViewForName.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class IncrementPageViewForName implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct(
public int $nameId
) {
}

public function handle(): void
{
// we use the DB facade and not the model for performance reasons
// if we call the model inside the job, the model will be serialized
// and will consume resources. we don't need to serialize the model for
// this operation.
DB::table('names')
->where('id', $this->nameId)
->increment('page_views');
}
}
26 changes: 26 additions & 0 deletions tests/Unit/Jobs/IncrementPageViewForNameTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Tests\Unit\Jobs;

use App\Jobs\IncrementPageViewForName;
use App\Models\Name;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;

class IncrementPageViewForNameTest extends TestCase
{
use DatabaseTransactions;

/** @test */
public function it_increments_the_page_view_for_a_name(): void
{
$name = Name::factory()->create();

IncrementPageViewForName::dispatch($name->id);

$this->assertDatabaseHas('names', [
'id' => $name->id,
'page_views' => 2,
]);
}
}

0 comments on commit 4181d58

Please sign in to comment.