Skip to content

Commit

Permalink
always return stale on rejection (#169)
Browse files Browse the repository at this point in the history
  • Loading branch information
e-zannelli authored Nov 9, 2023
1 parent 65f85ca commit 6bd64db
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
8 changes: 3 additions & 5 deletions src/CacheMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -237,11 +237,9 @@ function (ResponseInterface $response) use ($request, $cacheEntry) {
return static::addToCache($this->cacheStorage, $request, $response, $update);
},
function ($reason) use ($cacheEntry) {
if ($reason instanceof TransferException) {
$response = static::getStaleResponse($cacheEntry);
if ($response instanceof ResponseInterface) {
return $response;
}
$response = static::getStaleResponse($cacheEntry);
if ($response instanceof ResponseInterface) {
return $response;
}

return new RejectedPromise($reason);
Expand Down
23 changes: 23 additions & 0 deletions tests/CacheMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace Kevinrob\GuzzleCache\Tests;

use GuzzleHttp\Promise\RejectedPromise;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Utils;
use Kevinrob\GuzzleCache\CacheEntry;
use Kevinrob\GuzzleCache\CacheMiddleware as BaseCacheMiddleware;
use Kevinrob\GuzzleCache\Storage\Psr6CacheStorage;
use Kevinrob\GuzzleCache\Strategy\CacheStrategyInterface;
Expand Down Expand Up @@ -35,6 +37,27 @@ public function testRewindAfterReadingStream()

$this->assertEquals('seekable stream', $response->getBody()->getContents());
}

public function testStaleOnRejected()
{
$request = new Request('GET', '/uri');
$response = (new Response())->withHeader('Cache-Control', 'stale-if-error=120');
$strategy = $this->createStub(CacheStrategyInterface::class);
$strategy->method('fetch')->willReturn(new CacheEntry(
$request,
$response,
new \DateTime('-1 second')
));
$handler = function () {
return new RejectedPromise(new \RuntimeException('Unexpected error'));
};
$middleware = new CacheMiddleware($strategy);

$result = ($middleware($handler)($request, []))->wait();

$this->assertInstanceOf(ResponseInterface::class, $result);
$this->assertEquals(CacheMiddleware::HEADER_CACHE_STALE, $result->getHeaderLine(CacheMiddleware::HEADER_CACHE_INFO));
}
}

class CacheMiddleware extends BaseCacheMiddleware
Expand Down

0 comments on commit 6bd64db

Please sign in to comment.