Skip to content

Commit 8f5465a

Browse files
authored
Merge pull request #561 from favicode/graphql-stale-content
GraphQL header directive stale-while-revalidate
2 parents 75164a4 + 77014d7 commit 8f5465a

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Diff for: Plugin/GraphQl/AfterRenderResult.php

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace Fastly\Cdn\Plugin\GraphQl;
5+
6+
use Magento\Framework\App\ResponseInterface;
7+
use Magento\Framework\Controller\ResultInterface;
8+
use Magento\GraphQlCache\Model\CacheableQuery;
9+
use Fastly\Cdn\Model\Config;
10+
11+
class AfterRenderResult
12+
{
13+
/**
14+
* @var Config
15+
*/
16+
private $config;
17+
18+
/**
19+
* @var CacheableQuery
20+
*/
21+
private $cacheableQuery;
22+
23+
/**
24+
* AfterRenderResult constructor.
25+
*
26+
* @param Config $config
27+
* @param CacheableQuery $cacheableQuery
28+
*/
29+
public function __construct(
30+
Config $config,
31+
CacheableQuery $cacheableQuery
32+
) {
33+
$this->config = $config;
34+
$this->cacheableQuery = $cacheableQuery;
35+
}
36+
37+
/**
38+
* Add header directive stale-while-revalidate
39+
*
40+
* @param ResultInterface $subject
41+
* @param ResultInterface $result
42+
* @param ResponseInterface $response
43+
* @return ResultInterface
44+
*/
45+
public function afterRenderResult(
46+
ResultInterface $subject,
47+
ResultInterface $result,
48+
ResponseInterface $response
49+
): ResultInterface {
50+
if ($this->config->isEnabled()
51+
&& $this->config->getType() === Config::FASTLY
52+
&& $this->cacheableQuery->isCacheable()) {
53+
$header = $response->getHeader('cache-control');
54+
if ($header && $ttl = $this->config->getStaleTtl()) {
55+
$header->addDirective('stale-while-revalidate', $ttl);
56+
}
57+
}
58+
return $result;
59+
}
60+
}

Diff for: etc/graphql/di.xml

+3
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,7 @@
66
<type name="Magento\GraphQl\Controller\GraphQl">
77
<plugin name="fastly_graphql_rate_limiter" type="Fastly\Cdn\Model\FrontControllerPlugin" sortOrder="1"/>
88
</type>
9+
<type name="Magento\Framework\Controller\ResultInterface">
10+
<plugin name="fastly-graphql-stale-header" type="Fastly\Cdn\Plugin\GraphQl\AfterRenderResult"/>
11+
</type>
912
</config>

0 commit comments

Comments
 (0)