Skip to content

Commit 2fd8743

Browse files
committed
feat: Delegate recording blog post views to background jobs
1 parent 2794f78 commit 2fd8743

File tree

3 files changed

+61
-38
lines changed

3 files changed

+61
-38
lines changed

app/Actions/RecordBlogPostViewAction.php

Lines changed: 0 additions & 34 deletions
This file was deleted.

app/Http/Controllers/BlogController.php

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
namespace App\Http\Controllers;
44

5-
use App\Actions\RecordBlogPostViewAction;
65
use App\Http\Resources\BlogPostResource;
6+
use App\Jobs\RecordBlogPostViewsJob;
77
use App\Models\BlogPost;
8-
use Auth;
8+
use Illuminate\Support\Facades\Auth;
99
use Inertia\Inertia;
1010

1111
class BlogController extends Controller
@@ -23,7 +23,7 @@ public function index()
2323
]);
2424
}
2525

26-
public function show(string $slug, RecordBlogPostViewAction $recordViewAction)
26+
public function show(string $slug)
2727
{
2828
$blogPost = BlogPost::with(['categories'])
2929
->where('slug', $slug);
@@ -34,7 +34,12 @@ public function show(string $slug, RecordBlogPostViewAction $recordViewAction)
3434

3535
$blogPost = $blogPost->firstOrFail();
3636

37-
$recordViewAction->handle($blogPost, request());
37+
RecordBlogPostViewsJob::dispatch(
38+
$blogPost->id,
39+
request()->ip(),
40+
request()->userAgent(),
41+
request()->session()->getId()
42+
);
3843

3944
return Inertia::render('BlogPost', [
4045
'blogPost' => new BlogPostResource($blogPost),
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?php
2+
3+
namespace App\Jobs;
4+
5+
use App\Models\BlogPostView;
6+
use Illuminate\Contracts\Queue\ShouldQueue;
7+
use Illuminate\Foundation\Queue\Queueable;
8+
9+
class RecordBlogPostViewsJob implements ShouldQueue
10+
{
11+
use Queueable;
12+
13+
/**
14+
* Create a new job instance.
15+
*/
16+
public function __construct(
17+
public readonly int $blogPostId,
18+
public readonly string $ipAddress,
19+
public readonly ?string $userAgent,
20+
public readonly ?string $sessionId
21+
) {}
22+
23+
/**
24+
* Execute the job.
25+
*/
26+
public function handle(): void
27+
{
28+
$view = BlogPostView::query()
29+
->where('blog_post_id', $this->blogPostId)
30+
->where('ip_address', $this->ipAddress)
31+
->where('user_agent', $this->userAgent)
32+
->where('session_id', $this->sessionId)
33+
->first();
34+
35+
if (! $view) {
36+
BlogPostView::query()->create([
37+
'blog_post_id' => $this->blogPostId,
38+
'ip_address' => $this->ipAddress,
39+
'user_agent' => $this->userAgent,
40+
'session_id' => $this->sessionId,
41+
]);
42+
}
43+
}
44+
45+
public function tags()
46+
{
47+
return [
48+
'RecordBlogPostViewsJob',
49+
'BlogPost:'.$this->blogPostId,
50+
];
51+
}
52+
}

0 commit comments

Comments
 (0)