Files
sembara/app/Services/InsForge/InsForgeClient.php
T

141 lines
4.7 KiB
PHP

<?php
namespace App\Services\InsForge;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
class InsForgeClient
{
public function __construct(
private readonly string $baseUrl,
private readonly string $apiKey,
private readonly int $timeout = 30,
private readonly ?string $accessToken = null,
) {}
public function withToken(?string $accessToken): self
{
return new self($this->baseUrl, $this->apiKey, $this->timeout, $accessToken);
}
public function accessToken(): ?string
{
return $this->accessToken;
}
public function login(string $email, string $password): array
{
return $this->request('POST', '/api/auth/sessions', ['email' => $email, 'password' => $password])->json();
}
public function logout(): array
{
return $this->request('POST', '/api/auth/logout')->json();
}
public function currentUser(): array
{
return $this->request('GET', '/api/auth/profiles/current')->json();
}
public function listRecords(string $table, array $params = []): array
{
return $this->request('GET', "/api/database/records/{$table}", query: $params)->json() ?? [];
}
public function getRecord(string $table, string $id, array $params = []): ?array
{
$params['id'] = 'eq.'.$id;
$params['limit'] = 1;
return $this->listRecords($table, $params)[0] ?? null;
}
public function insertRecord(string $table, array $data, bool $asUser = true): array
{
return $this->request('POST', "/api/database/records/{$table}", $data, asUser: $asUser)->json();
}
public function updateRecords(string $table, array $filters, array $data, bool $asUser = true): array
{
$query = $this->buildFilters($filters);
return $this->request('PATCH', "/api/database/records/{$table}", $data, query: $query, asUser: $asUser)->json();
}
public function deleteRecords(string $table, array $filters, bool $asUser = true): array
{
return $this->request('DELETE', "/api/database/records/{$table}", query: $this->buildFilters($filters), asUser: $asUser)->json();
}
public function countRecords(string $table, array $filters = []): int
{
$query = $this->buildFilters($filters);
$response = $this->request('HEAD', "/api/database/records/{$table}", query: array_merge($query, ['limit' => 1]));
return (int) ($response->header('Content-Range') ? explode('/', explode('-', $response->header('Content-Range'))[1])[0] : 0);
}
public function rpc(string $function, array $args = [], bool $asUser = true): mixed
{
return $this->request('POST', "/api/database/rpc/{$function}", $args, asUser: $asUser)->json();
}
public function createUserAsAdmin(array $payload): array
{
return $this->request('POST', '/api/auth/users', $payload)->json();
}
public function updateUserAsAdmin(string $userId, array $payload): array
{
return $this->request('PATCH', "/api/auth/users/{$userId}", $payload)->json();
}
private function buildFilters(array $filters): array
{
$query = [];
foreach ($filters as $column => $value) {
$query[$column] = str_starts_with((string) $value, 'eq.') ? $value : 'eq.'.$value;
}
return $query;
}
public function send(string $method, string $path, array $body = [], array $query = [], bool $asUser = false, array $headers = []): Response
{
if ($asUser && $this->accessToken === null) {
throw new InsForgeException(null, 401, 'No user access token available for this request.');
}
try {
$http = Http::baseUrl(rtrim($this->baseUrl, '/'))
->timeout($this->timeout)
->withHeaders($headers)
->withToken($asUser ? $this->accessToken : $this->apiKey);
$verb = strtolower($method);
$response = in_array($verb, ['get', 'head'])
? $http->{$verb}($path, $query)
: $http->{$verb}($path, $body);
throw_unless($response->successful(), fn () => InsForgeException::fromResponse(
$response->status(),
$response->json() ?? $response->body(),
));
return $response;
} catch (ConnectionException $e) {
throw new InsForgeException(null, 0, 'InsForge connection failed: '.$e->getMessage());
}
}
private function request(string $method, string $path, ?array $body = null, array $query = [], bool $asUser = false): Response
{
return $this->send($method, $path, $body ?? [], $query, $asUser);
}
}