Skip to content

Commit

Permalink
feat: Add health endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
keriati committed Dec 11, 2022
1 parent 11257a2 commit 751b23a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
58 changes: 58 additions & 0 deletions app/Http/Controllers/HealthController.php
Original file line number Diff line number Diff line change
@@ -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(),
]);
}
}
3 changes: 3 additions & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -111,3 +112,5 @@

Route::resource('api/item', ItemRestController::class);
Route::get('import', ImportController::class)->name('items.import');

Route::get('/health', HealthController::class)->name('health');

0 comments on commit 751b23a

Please sign in to comment.