feat: Add health endpoint

This commit is contained in:
Attila Kerekes 2022-12-11 00:31:30 +01:00
parent 11257a272e
commit 751b23a5e4
2 changed files with 61 additions and 0 deletions

View file

@ -0,0 +1,58 @@
<?php
namespace App\Http\Controllers;
use App\Item;
use App\User;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\RateLimiter;
class HealthController extends Controller
{
/**
* @return int
*/
private static function getUsers(): int
{
return User::count();
}
/**
* @return int
*/
private static function getItems(): int
{
return Item::select('id')
->where('deleted_at', null)
->where('type', '0')
->count();
}
/**
* Handle the incoming request.
*
* @param Request $request
* @return JsonResponse|Response
* @throws BindingResolutionException
*/
public function __invoke(Request $request)
{
$REQUESTS_MAX_PER_MIN = 30;
$STATUS_TOO_MANY_REQUESTS = 429;
if (RateLimiter::remaining('health', $REQUESTS_MAX_PER_MIN) < 1) {
return response()->make('Too many attempts.', $STATUS_TOO_MANY_REQUESTS);
}
RateLimiter::hit('health');
return response()->json([
'status' => 'ok',
'items' => self::getItems(),
'users' => self::getUsers(),
]);
}
}

View file

@ -2,6 +2,7 @@
use App\Application;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\HealthController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ImportController;
use App\Http\Controllers\ItemController;
@ -111,3 +112,5 @@ Route::get('/home', [HomeController::class,'index'])->name('home');
Route::resource('api/item', ItemRestController::class);
Route::get('import', ImportController::class)->name('items.import');
Route::get('/health', HealthController::class)->name('health');