Skip to content

Commit 109b74d

Browse files
committed
feat(proxy): add cache for http proxy
1 parent ed33450 commit 109b74d

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/Controller/MediaProxyController.php

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,16 @@
1010
use Symfony\Component\HttpFoundation\Request;
1111
use Symfony\Component\HttpFoundation\Response;
1212
use Symfony\Component\Routing\Attribute\Route;
13+
use Symfony\Contracts\Cache\CacheInterface;
14+
use Symfony\Contracts\Cache\ItemInterface;
1315
use Symfony\Contracts\HttpClient\HttpClientInterface;
1416

1517
#[Route(defaults: ['_routeScope' => ['api']])]
1618
class MediaProxyController extends AbstractController
1719
{
1820
public function __construct(
1921
private HttpClientInterface $client,
22+
private CacheInterface $cache,
2023
) {
2124
}
2225

@@ -49,13 +52,26 @@ public function execute(Request $request): Response
4952
return $this->malformedRequestError();
5053
}
5154

52-
$response = $this->client->request('GET', $url);
55+
$response = $this->cache->get($url, function (ItemInterface $item) use ($url): array {
56+
$response = $this->client->request('GET', $url);
57+
$statusCode = $response->getStatusCode();
5358

54-
if (Response::HTTP_OK !== $response->getStatusCode()) {
55-
return new Response(status: $response->getStatusCode());
59+
if (Response::HTTP_OK !== $statusCode) {
60+
// do not cache error / not found responses
61+
$item->expiresAfter(0);
62+
}
63+
64+
return [
65+
'statusCode' => $statusCode,
66+
'content' => $response->getContent(false),
67+
];
68+
});
69+
70+
if (Response::HTTP_OK !== $response['statusCode']) {
71+
new Response(status: $response['statusCode']);
5672
}
5773

58-
return new Response($response->getContent());
74+
return new Response($response['content']);
5975
}
6076

6177
protected function malformedRequestError(): Response

src/Resources/config/services.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090

9191
<service id="NuonicPluginInstaller\Controller\MediaProxyController">
9292
<argument type="service" id="http_client" />
93+
<argument type="service" id="cache.app" />
9394
<call method="setContainer">
9495
<argument type="service" id="service_container"/>
9596
</call>

0 commit comments

Comments
 (0)