initial commit
This commit is contained in:
commit
3f64f4a49a
221 files changed
+26665
No files matched your search
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Api;
|
||||
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Support\Validator;
|
||||
|
||||
/**
|
||||
* Основа контроллеров API: единый формат ответа.
|
||||
*
|
||||
* Успех — {"data": …}, ошибка — {"error": {"message": …, "status": …}}.
|
||||
* Клиенту не приходится гадать, что он получил.
|
||||
*/
|
||||
abstract class ApiController extends Controller
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed>|array<int, mixed> $data
|
||||
* @param array<string, mixed> $meta
|
||||
*/
|
||||
protected function data(array $data, int $status = 200, array $meta = []): Response
|
||||
{
|
||||
$payload = ['data' => $data];
|
||||
|
||||
if ($meta !== []) {
|
||||
$payload['meta'] = $meta;
|
||||
}
|
||||
|
||||
return Response::json($payload, $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Страница списка вместе со счётчиками.
|
||||
*
|
||||
* @param array{items: array<int, mixed>, total: int, page: int, pages: int, per_page: int} $page
|
||||
* @param callable(mixed): array<string, mixed> $map как превратить запись в ответ
|
||||
*/
|
||||
protected function paginated(array $page, callable $map): Response
|
||||
{
|
||||
return $this->data(
|
||||
array_map($map, $page['items']),
|
||||
200,
|
||||
['total' => $page['total'], 'page' => $page['page'], 'pages' => $page['pages'], 'per_page' => $page['per_page']]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Разбор тела запроса с понятной ошибкой на сломанном JSON: «пустое тело»
|
||||
* и «опечатка в кавычке» — разные беды, и искать их надо в разных местах.
|
||||
*
|
||||
* @param array<string, string> $rules
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function payload(Request $request, array $rules): array
|
||||
{
|
||||
$error = $request->bodyError();
|
||||
|
||||
if ($error !== null) {
|
||||
throw new \Rsgrinko\Proton\Support\ProtonException($error, [], 400);
|
||||
}
|
||||
|
||||
return Validator::make($request->all(), $rules)->validate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Api;
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Access\Scope;
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
|
||||
/**
|
||||
* Заметки через API — тот же раздел, что и в вебе, только для машин.
|
||||
*
|
||||
* Область видимости здесь та же: ключ принадлежит человеку, и через него
|
||||
* доступны ровно его записи. Чужая заметка не существует — 404, а не 403.
|
||||
*/
|
||||
final class NotesController extends ApiController
|
||||
{
|
||||
public function index(Request $request, Scope $scope): Response
|
||||
{
|
||||
$query = $scope->apply(Note::query())
|
||||
->when($request->text('q'), static fn ($query, string $needle) => $query->whereLike('title', $needle))
|
||||
->orderBy('id', 'desc');
|
||||
|
||||
return $this->paginated(
|
||||
$query->paginate($this->page($request), $this->perPage()),
|
||||
static fn (Note $note): array => $note->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
public function show(int $id, Scope $scope): Response
|
||||
{
|
||||
/** @var Note|null $note */
|
||||
$note = $scope->apply(Note::query())->where('id', $id)->first();
|
||||
|
||||
if ($note === null) {
|
||||
return Response::error('Заметка не найдена', 404);
|
||||
}
|
||||
|
||||
return $this->data($note->toArray());
|
||||
}
|
||||
|
||||
public function store(Request $request, Viewer $viewer): Response
|
||||
{
|
||||
$data = $this->payload($request, [
|
||||
'title' => 'required|max:191',
|
||||
'body' => 'nullable|max:20000',
|
||||
'pinned' => 'nullable|boolean',
|
||||
]);
|
||||
|
||||
$note = new Note($data);
|
||||
|
||||
$note->setAttribute('user_id', $viewer->id());
|
||||
$note->save();
|
||||
|
||||
Audit::created('note', $note->id(), 'заметка через API: ' . (string) $note->title);
|
||||
|
||||
return $this->data($note->toArray(), 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, int $id, Scope $scope): Response
|
||||
{
|
||||
/** @var Note|null $note */
|
||||
$note = $scope->apply(Note::query())->where('id', $id)->first();
|
||||
|
||||
if ($note === null) {
|
||||
return Response::error('Заметка не найдена', 404);
|
||||
}
|
||||
|
||||
$data = $this->payload($request, [
|
||||
'title' => 'nullable|max:191',
|
||||
'body' => 'nullable|max:20000',
|
||||
'pinned' => 'nullable|boolean',
|
||||
]);
|
||||
|
||||
// Пустые поля не затираем: PATCH меняет то, что прислали
|
||||
$note->fill(array_filter($data, static fn (mixed $value): bool => $value !== null));
|
||||
$note->save();
|
||||
|
||||
Audit::updated('note', $note->id(), 'заметка через API: ' . (string) $note->title);
|
||||
|
||||
return $this->data($note->toArray());
|
||||
}
|
||||
|
||||
public function delete(int $id, Scope $scope): Response
|
||||
{
|
||||
/** @var Note|null $note */
|
||||
$note = $scope->apply(Note::query())->where('id', $id)->first();
|
||||
|
||||
if ($note === null) {
|
||||
return Response::error('Заметка не найдена', 404);
|
||||
}
|
||||
|
||||
$note->delete();
|
||||
|
||||
Audit::deleted('note', $id, 'заметка через API');
|
||||
|
||||
return $this->data(['deleted' => true]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Api;
|
||||
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Models\ApiToken;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Queue\Queue;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Служебные адреса API: кто я и жив ли сервис.
|
||||
*/
|
||||
final class SystemController extends ApiController
|
||||
{
|
||||
/**
|
||||
* Кто пришёл по ключу. Первое, что дёргают при отладке интеграции.
|
||||
*/
|
||||
public function me(Viewer $viewer, User $user, ApiToken $token): Response
|
||||
{
|
||||
return $this->data([
|
||||
'user' => [
|
||||
'id' => $user->id(),
|
||||
'login' => (string) $user->login,
|
||||
'name' => (string) $user->name,
|
||||
'email' => (string) $user->email,
|
||||
'permissions' => $viewer->permissions(),
|
||||
],
|
||||
'token' => [
|
||||
'id' => $token->id(),
|
||||
'name' => (string) $token->name,
|
||||
'mask' => $token->mask(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Здоровье сервиса — его дёргает мониторинг, поэтому ключ здесь не нужен.
|
||||
* Наружу отдаём только то, что не жалко: живость базы и размер очереди.
|
||||
*/
|
||||
public function health(): Response
|
||||
{
|
||||
$database = 'ok';
|
||||
|
||||
try {
|
||||
Connection::instance()->value('SELECT 1');
|
||||
} catch (Throwable $e) {
|
||||
$database = 'fail';
|
||||
}
|
||||
|
||||
$queue = [];
|
||||
|
||||
try {
|
||||
$queue = Queue::stats();
|
||||
} catch (Throwable) {
|
||||
$database = 'fail';
|
||||
}
|
||||
|
||||
$healthy = $database === 'ok';
|
||||
|
||||
return Response::json([
|
||||
'status' => $healthy ? 'ok' : 'fail',
|
||||
'app' => (string) Config::get('app.name', 'Proton'),
|
||||
'database' => $database,
|
||||
'queue' => $queue,
|
||||
'time' => date('c'),
|
||||
], $healthy ? 200 : 503);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user