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 10, 2022
1 parent 11257a2 commit 2c41c65
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
55 changes: 55 additions & 0 deletions app/Http/Controllers/HealthController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?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)
{
if ((int) RateLimiter::remaining('health', 30) < 1) {
return response()->make('Too many attempts.', 429);
}

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 2c41c65

Please sign in to comment.