Skip to content

Instantly share code, notes, and snippets.

@ibrahim-dogan
Created October 14, 2021 09:03
Show Gist options
  • Save ibrahim-dogan/989abafdb0219c3aa2be41e9c9e13af7 to your computer and use it in GitHub Desktop.
Save ibrahim-dogan/989abafdb0219c3aa2be41e9c9e13af7 to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Controllers;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class HealthController extends Controller
{
/**
* Health check for api
*
* @return JsonResponse
*/
public function check(): JsonResponse
{
$dbStatus = $this->isDatabaseReady();
$redisStatus = $this->isRedisReady();
$status = $dbStatus && $redisStatus;
return response()->json(
["status" => $status],
$status ? 200 : 500
);
}
/**
* Check database connection
* @param null $connection
* @return bool
*/
private function isDatabaseReady($connection = null): bool
{
$isReady = true;
try {
DB::connection($connection)->statement("select 1");
} catch (Exception $e) {
Log::error("HealthController@isDatabaseReady", [$e->getMessage()]);
$isReady = false;
}
return $isReady;
}
/**
* Check redis connection
* @param null $connection
* @return bool
*/
private function isRedisReady($connection = null): bool
{
$isReady = true;
try {
Redis::connection($connection)->ping();
} catch (Exception $e) {
Log::error("HealthController@isRedisReady", [$e->getMessage()]);
$isReady = false;
}
return $isReady;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment