feat(*.php, *.psql): deduplicate API code + performance improvements
This commit is contained in:
parent
cf3dac8a46
commit
4bad005e58
31 changed files with 502 additions and 666 deletions
|
@ -1,72 +1,15 @@
|
|||
<?php
|
||||
|
||||
namespace App\Classes;
|
||||
use GuzzleHttp\Client;
|
||||
|
||||
require __DIR__ . "/../../vendor/autoload.php";
|
||||
require __DIR__ . "/BaseHandler.php";
|
||||
|
||||
abstract class ApiHandler
|
||||
abstract class ApiHandler extends BaseHandler
|
||||
{
|
||||
protected string $postgrestUrl;
|
||||
protected string $postgrestApiKey;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->loadEnvironment();
|
||||
}
|
||||
|
||||
private function loadEnvironment(): void
|
||||
{
|
||||
$this->postgrestUrl =
|
||||
$_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL") ?: "";
|
||||
$this->postgrestApiKey =
|
||||
$_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY") ?: "";
|
||||
}
|
||||
|
||||
protected function ensureCliAccess(): void
|
||||
{
|
||||
if (php_sapi_name() !== "cli" && $_SERVER["REQUEST_METHOD"] !== "POST") {
|
||||
$this->redirectNotFound();
|
||||
if (php_sapi_name() !== 'cli' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
$this->sendErrorResponse("Not Found", 404);
|
||||
}
|
||||
}
|
||||
|
||||
protected function redirectNotFound(): void
|
||||
{
|
||||
header("Location: /404", true, 302);
|
||||
exit();
|
||||
}
|
||||
|
||||
protected function fetchFromPostgREST(
|
||||
string $endpoint,
|
||||
string $query = "",
|
||||
string $method = "GET",
|
||||
?array $body = null
|
||||
): array {
|
||||
$url = "{$this->postgrestUrl}/{$endpoint}?{$query}";
|
||||
$options = [
|
||||
"headers" => [
|
||||
"Content-Type" => "application/json",
|
||||
"Authorization" => "Bearer {$this->postgrestApiKey}",
|
||||
],
|
||||
];
|
||||
|
||||
if ($method === "POST" && $body) $options["json"] = $body;
|
||||
|
||||
$response = (new Client())->request($method, $url, $options);
|
||||
|
||||
return json_decode($response->getBody(), true) ?? [];
|
||||
}
|
||||
|
||||
protected function sendResponse(string $message, int $statusCode): void
|
||||
{
|
||||
http_response_code($statusCode);
|
||||
header("Content-Type: application/json");
|
||||
echo json_encode(["message" => $message]);
|
||||
exit();
|
||||
}
|
||||
|
||||
protected function sendErrorResponse(string $message, int $statusCode): void
|
||||
{
|
||||
$this->sendResponse($message, $statusCode);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue