Move caching logic to response

This avoids having to do it at all the places we want cached responses.

We can't inject the ITimeFactor without breaking public API.
However we can perfectly overwrite the service (resulting in the same
testable effect).

Signed-off-by: Roeland Jago Douma <roeland@famdouma.nl>
This commit is contained in:
Roeland Jago Douma 2018-05-29 11:10:07 +02:00
parent 36d74047f7
commit a34495933e
No known key found for this signature in database
GPG Key ID: F941078878347C0C
2 changed files with 26 additions and 4 deletions

View File

@ -35,6 +35,7 @@
namespace OCP\AppFramework\Http;
use OCP\AppFramework\Http;
use OCP\AppFramework\Utility\ITimeFactory;
/**
* Base class for responses. Also used to just send headers.
@ -95,12 +96,23 @@ class Response {
* @return $this
* @since 6.0.0 - return value was added in 7.0.0
*/
public function cacheFor($cacheSeconds) {
public function cacheFor(int $cacheSeconds) {
if($cacheSeconds > 0) {
$this->addHeader('Cache-Control', 'max-age=' . $cacheSeconds . ', must-revalidate');
// Old scool prama caching
$this->addHeader('Pragma', 'public');
// Set expires header
$expires = new \DateTime();
/** @var ITimeFactory $time */
$time = \OC::$server->query(ITimeFactory::class);
$expires->setTimestamp($time->getTime());
$expires->add(new \DateInterval('PT'.$cacheSeconds.'S'));
$this->addHeader('Expires', $expires->format(\DateTime::RFC2822));
} else {
$this->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
unset($this->headers['Expires'], $this->headers['Pragma']);
}
return $this;

View File

@ -27,6 +27,7 @@ namespace Test\AppFramework\Http;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http;
use OCP\AppFramework\Utility\ITimeFactory;
class ResponseTest extends \Test\TestCase {
@ -222,15 +223,24 @@ class ResponseTest extends \Test\TestCase {
$headers = $this->childResponse->getHeaders();
$this->assertEquals('no-cache, no-store, must-revalidate', $headers['Cache-Control']);
$this->assertFalse(isset($headers['Pragma']));
$this->assertFalse(isset($headers['Expires']));
}
public function testCacheSeconds() {
$time = $this->createMock(ITimeFactory::class);
$time->method('getTime')
->willReturn('1234567');
$this->overwriteService(ITimeFactory::class, $time);
$this->childResponse->cacheFor(33);
$headers = $this->childResponse->getHeaders();
$this->assertEquals('max-age=33, must-revalidate',
$headers['Cache-Control']);
$this->assertEquals('max-age=33, must-revalidate', $headers['Cache-Control']);
$this->assertEquals('public', $headers['Pragma']);
$this->assertEquals('Thu, 15 Jan 1970 06:56:40 +0000', $headers['Expires']);
}