diff --git a/app/Checkers/Uptime.php b/app/Checkers/Uptime.php index cfc433d..f02e1f4 100644 --- a/app/Checkers/Uptime.php +++ b/app/Checkers/Uptime.php @@ -23,6 +23,7 @@ public function run() { $this->fetch(); $this->notify(); + $this->cache(); } private function fetch() @@ -86,4 +87,9 @@ private function notify() ); } } + + private function cache() + { + $this->website->generateUptimeReport(true); + } } diff --git a/app/HasUptime.php b/app/HasUptime.php index fa1aeed..4e0bfe8 100644 --- a/app/HasUptime.php +++ b/app/HasUptime.php @@ -8,7 +8,34 @@ trait HasUptime { public function uptimes() { - return $this->hasMany(UptimeScan::class)->orderBy('created_at', 'desc'); + return $this->hasMany(UptimeScan::class) + ->where('created_at', '<', now()->addDays(31)) + ->orderBy('created_at', 'desc'); + } + + public function generateUptimeReport($refreshCache = false) + { + if ($refreshCache) { + cache()->forget($this->cache_key); + $this->load(['uptimes']); + } + + return cache()->rememberForever($this->cache_key, function () { + return [ + 'uptime' => $this->uptime_summary, + 'response_time' => $this->response_time, + 'response_times' => $this->response_times, + 'online' => $this->current_state, + 'online_time' => $this->uptime, + 'last_incident' => $this->last_incident, + 'events' => $this->recent_events, + ]; + }); + } + + public function getCacheKeyAttribute() + { + return 'uptime_' . $this->getKey(); } public function getLastIncidentAttribute() diff --git a/app/Http/Controllers/UptimeReportController.php b/app/Http/Controllers/UptimeReportController.php index b41ce24..d02b3b3 100644 --- a/app/Http/Controllers/UptimeReportController.php +++ b/app/Http/Controllers/UptimeReportController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use Exception; use App\Website; use App\Jobs\UptimeCheck; use Illuminate\Http\Request; @@ -14,6 +15,7 @@ class UptimeReportController extends Controller * @param Request $request * @param Website $website * @return array + * @throws Exception */ public function __invoke(Request $request, Website $website) { @@ -21,17 +23,7 @@ public function __invoke(Request $request, Website $website) UptimeCheck::dispatchNow($website); } - $website->load(['uptimes']); - - $response = [ - 'uptime' => $website->uptime_summary, - 'response_time' => $website->response_time, - 'response_times' => $website->response_times, - 'online' => $website->current_state, - 'online_time' => $website->uptime, - 'last_incident' => $website->last_incident, - 'events' => $website->recent_events, - ]; + $response = $website->generateUptimeReport(); return response($response); }