From d24d49730457fbebc9c048adff112e5ffb9bf032 Mon Sep 17 00:00:00 2001 From: Sebastian Nowicki Date: Thu, 18 Apr 2019 15:57:25 +0200 Subject: [PATCH] Handle a TTL of 0 correctly When a TTL override of 0 is set, the override is overriden with the policy due to using the || operator, which considers 0 to be false. --- CHANGELOG.md | 1 + packages/apollo-datasource-rest/src/HTTPCache.ts | 2 +- .../src/__tests__/HTTPCache.test.ts | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35420adf7af..ab1f5e6ebde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ### vNEXT - Allow `GraphQLRequestListener` callbacks in plugins to depend on `this`. [PR #2470](https://github.com/apollographql/apollo-server/pull/2470) +- Handle a TTL value of 0 as not cachable. [PR #2588](https://github.com/apollographql/apollo-server/pull/2588) ### v2.4.8 diff --git a/packages/apollo-datasource-rest/src/HTTPCache.ts b/packages/apollo-datasource-rest/src/HTTPCache.ts index 22992051a96..4f083ee83ee 100644 --- a/packages/apollo-datasource-rest/src/HTTPCache.ts +++ b/packages/apollo-datasource-rest/src/HTTPCache.ts @@ -116,7 +116,7 @@ export class HTTPCache { return response; } - let ttl = ttlOverride || Math.round(policy.timeToLive() / 1000); + let ttl = ttlOverride === undefined ? Math.round(policy.timeToLive() / 1000) : ttlOverride; if (ttl <= 0) return response; // If a response can be revalidated, we don't want to remove it from the cache right after it expires. diff --git a/packages/apollo-datasource-rest/src/__tests__/HTTPCache.test.ts b/packages/apollo-datasource-rest/src/__tests__/HTTPCache.test.ts index bc5f1caf596..9be02a78828 100644 --- a/packages/apollo-datasource-rest/src/__tests__/HTTPCache.test.ts +++ b/packages/apollo-datasource-rest/src/__tests__/HTTPCache.test.ts @@ -210,6 +210,21 @@ describe('HTTPCache', () => { expect(await response.json()).toEqual({ name: 'Ada Lovelace' }); expect(response.headers.get('Age')).toEqual('10'); }); + + it('allows disabling caching when the TTL is 0 (falsy)', async () => { + fetch.mockJSONResponseOnce( + { name: 'Ada Lovelace' }, + { 'Cache-Control': 'max-age=30' }, + ); + + await httpCache.fetch(new Request('https://api.example.com/people/1'), { + cacheOptions: (response: Response, request: Request) => ({ + ttl: 0, + }), + }); + + expect(store.size).toEqual(0); + }); }); it('allows specifying a custom cache key', async () => {