Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions app/Http/Requests/CreateActivityRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
namespace App\Http\Requests;

use App\Enums\EventType;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

final class CreateActivityRequest extends FormRequest
{
Expand All @@ -27,4 +29,17 @@ public function rules(): array
],
];
}

protected function failedValidation(Validator $validator)
{
$errors = $validator->errors();
$errors->add('events', 'The events field is invalid.');

$response = response()->json([
'events' => 'The events field is invalid.',
'errors' => $validator->errors(),
], 422);

throw new ValidationException($validator, $response);
}
}
42 changes: 24 additions & 18 deletions app/Jobs/IngestActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,34 @@ public function handle(): void
$events = $this->activity->events;

collect($events)
->each(function (Event $event): void {
$path = $this->urlToPath($event->payload['url']);
$bucket = $this->bucket->setTime($this->bucket->hour, 0, 0);

/** @var Page $page */
$page = $this->activity->project->pages()->firstOrCreate([
'path' => $path,
'bucket' => $bucket,
], [
'views' => 0,
'average_time' => 0,
]);

match ($event->type) {
EventType::View => $this->handleView($page),
EventType::ViewDuration => $this->handleViewDuration($page, $event),
};
});
->each($this->processEvent(...));

$this->activity->delete();
}

/**
* Process the event.
*/
private function processEvent(Event $event): void
{
$path = $this->urlToPath($event->payload['url']);
$bucket = $this->bucket->setTime($this->bucket->hour, 0, 0);

/** @var Page $page */
$page = $this->activity->project->pages()->firstOrCreate([
'path' => $path,
'bucket' => $bucket,
], [
'views' => 0,
'average_time' => 0,
]);

match ($event->type) {
EventType::View => $this->handleView($page),
EventType::ViewDuration => $this->handleViewDuration($page, $event),
};
}

/**
* Handle the view event.
*/
Expand Down