federicozardi/laravel-http-utils

HTTP utilities for Laravel microservices: IncomingRequest, ExternalHttpClient, JwtUser(+Service).

Installs: 280

Dependents: 0

Suggesters: 0

Security: 0

pkg:composer/federicozardi/laravel-http-utils

v1.3.1 2025-11-27 10:24 UTC

This package is auto-updated.

Last update: 2025-12-27 10:43:19 UTC


README

Utility comuni per microservizi Laravel: IncomingRequest, ExternalHttpClient, JwtUser(+Service) e client specializzati come FileServiceClient.

Installazione

composer require federicozardi/laravel-http-utils
php artisan vendor:publish --tag=config

Configurazione

Imposta il base URL del file-service (se diverso dal default http://file-service/api):

FILE_SERVICE_BASE_URL=https://file-service.internal/api

Imposta il base URL del payment-service (prefisso rotte payment, default http://payment-service/api):

PAYMENT_SERVICE_BASE_URL=https://payment-service.internal/api

Esempi d'uso

IncomingRequest

use FedericoZardi\LaravelHttpUtils\Http\IncomingRequest;

class OrdersController
{
    public function index(IncomingRequest $request)
    {
        $user = $request->jwtUser();
        $corrId = $request->correlationId();
        // ...
    }
}

FileServiceClient

use FedericoZardi\LaravelHttpUtils\Services\FileServiceClient;

class DocsService
{
    public function __construct(private FileServiceClient $files) {}

    public function upload(string $localPath): array
    {
        return $this->files->uploadFile($localPath, 'documents/2025', ['category' => 'invoice']);
    }

    public function getPublicUrl(string $id): string
    {
        return $this->files->getFileUrl($id);
    }
}

Lista/Ricerca file

// Filtri espliciti + metadati custom
$result = $files->listFiles(
    custom_metadata: ['category' => 'invoice', 'department' => 'finance'],
    perPage: 10,
    page: 1,
    mimeType: 'application/pdf',
    userId: 'user-123',
);

// Struttura tipica
// [ 'success' => true, 'data' => [...], 'pagination' => [...] ]

Metadati file

$details = $files->getFile($fileId);

Download file

$response = $files->downloadFile($fileId);
$stream = $response->getBody();

URL pubblici e temporanei

$publicUrl = $files->getFileUrl($fileId);
$temporary = $files->getTemporaryUrl($fileId, expirationSeconds: 3600);
// $temporary -> [ 'success' => true, 'data' => ['url' => '...', 'expires_in' => 3600] ]

Eliminazione

$deleted = $files->deleteFile($fileId);

PaymentServiceClient

Solo rotte con prefisso payment/* del servizio payment-service.

use FedericoZardi\LaravelHttpUtils\Services\PaymentServiceClient;

class CheckoutService
{
    public function __construct(private PaymentServiceClient $payments) {}

    public function create(array $data): array
    {
        return $this->payments->createPayment($data); // POST /payments
    }

    public function parts(string $paymentId): array
    {
        return $this->payments->addPaymentParts($paymentId, [ // POST /payments/{id}/parts
            // ... payload con le nuove parts
        ]);
    }

    public function update(string $paymentId, array $data): array
    {
        return $this->payments->updatePayment($paymentId, $data); // PATCH /payments/{id}
    }

    public function delete(string $paymentId): bool
    {
        return $this->payments->deletePayment($paymentId); // DELETE /payments/{id}
    }
}

ExternalHttpClient

Il client inoltra automaticamente header JWT e X-Correlation-ID dalla richiesta in ingresso.

use FedericoZardi\LaravelHttpUtils\Services\ExternalHttpClient;

class InventoryService
{
    public function __construct(private ExternalHttpClient $http) {}

    public function getStock(string $sku): array
    {
        $resp = $this->http->get("https://inventory.svc/api/stock/{$sku}");
        return json_decode((string) $resp->getBody(), true);
    }
}

Disabilitare il logging HTTP per evitare loop

Per richieste che non devono generare log (es. invio dei log a un log-service), usa requestNoLog o passa l'opzione http_logging_disabled.

// API esplicita
$resp = $http->requestNoLog('POST', 'http://log-service/api/logs', [
    'json' => $payload,
]);

// Oppure via opzione (equivalente)
$resp = $http->post('http://log-service/api/logs', [
    'json' => $payload,
    'http_logging_disabled' => true, // aggiunge X-Disable-Http-Logging: 1 e sopprime i log external_http.*
]);

Quando http_logging_disabled è attivo, il client:

  • imposta l'header X-Disable-Http-Logging: 1;
  • sopprime i log external_http.request.* e external_http.forward_headers;
  • continua a inoltrare gli header standard (JWT, X-Correlation-ID).

JwtUserService

use FedericoZardi\LaravelHttpUtils\Services\JwtUserService;

class SomeService
{
    public function __construct(private JwtUserService $jwt) {}

    public function current(): array
    {
        return $this->jwt->extractUserFromJwt();
    }
}

Note

  • Per impostazione predefinita FileServiceClient usa FILE_SERVICE_BASE_URL o http://file-service/api.
  • Vengono inoltrati jwt_headers da config/http-utils.php e X-Correlation-ID.
  • La decodifica JWT è senza verifica firma: si assume trust del gateway.