41 lines
1.3 KiB
PHP
41 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Controller\Api;
|
|
|
|
use App\BusProNet\Client\TravelClient;
|
|
use App\BusProNet\Exception\ApiClientException;
|
|
use Psr\Cache\InvalidArgumentException;
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\HttpFoundation\JsonResponse;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
|
use Symfony\Contracts\Cache\CacheInterface;
|
|
use Symfony\Contracts\Cache\ItemInterface;
|
|
|
|
#[Route('/api')]
|
|
#[IsGranted('ROLE_OAUTH2_API')]
|
|
class ProductController extends AbstractController
|
|
{
|
|
public function __construct(
|
|
private readonly TravelClient $travelClient,
|
|
private readonly CacheInterface $cache,
|
|
) {
|
|
}
|
|
|
|
#[Route(path: '/products', name: 'api_products')]
|
|
public function index(): JsonResponse
|
|
{
|
|
try {
|
|
$products = $this->cache->get('api_products', function (ItemInterface $item) {
|
|
$item->expiresAfter(3600); // 1 hour cache
|
|
|
|
return $this->travelClient->getProducts();
|
|
});
|
|
|
|
return $this->json($products);
|
|
} catch (InvalidArgumentException|ApiClientException $e) {
|
|
return $this->json(['error' => $e->getMessage(), 'type' => 'api_error']);
|
|
}
|
|
}
|
|
}
|