Skip to content

Commit

Permalink
feat: add updateTTLOnGet argument to cache middleware (#132)
Browse files Browse the repository at this point in the history
* Add updateTTLOnGet argument to refresh cache ttl on cache get

* Update tests to test updateTTLOnGet option

* Update typescript types for updateTTLOnGet

* Update readme for updateTTLOnGet

* Reset linting on src/index.d.ts
  • Loading branch information
dr3 authored Aug 22, 2021
1 parent 4453ece commit 333a1c3
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import { RelayNetworkLayer } from 'react-relay-network-modern/es';
- `allowFormData` - allow to cache FormData requests (default: `false`)
- `clearOnMutation` - clear the cache on any Mutation (default: `false`)
- `cacheErrors` - cache responses with errors (default: `false`)
- `updateTTLOnGet` - refresh cache ttl on queries on successful cache get (default: `false`)
- **authMiddleware** - for adding auth token, and refreshing it if gets 401 response from server.
- `token` - string which returns token. Can be function(req) or Promise. If function is provided, then it will be called for every request (so you may change tokens on fly).
- `tokenRefreshPromise`: - function(req, res) which must return promise or regular value with a new token. This function is called when server returns 401 status code. After receiving a new token, middleware re-run query to the server seamlessly for Relay.
Expand Down
1 change: 1 addition & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ export interface CacheMiddlewareOpts {
allowFormData?: boolean;
clearOnMutation?: boolean;
cacheErrors?: boolean;
updateTTLOnGet?: boolean;
}

export function cacheMiddleware(opts?: CacheMiddlewareOpts): Middleware;
Expand Down
37 changes: 37 additions & 0 deletions src/middlewares/__tests__/cache-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,41 @@ describe('middlewares/cache', () => {
await expect(mockReq('FirstQuery').execute(rnl)).rejects.toThrow();
expect(fetchMock.calls('/graphql')).toHaveLength(1);
});

it('updates ttl on get if updateTTLOnGet is set', async () => {
fetchMock.mock({
matcher: '/graphql',
response: {
status: 200,
body: { data: 'PAYLOAD' },
},
method: 'POST',
});

const rnl = new RelayNetworkLayer([
cacheMiddleware({
ttl: 30,
updateTTLOnGet: true,
}),
]);

// data from fetch
const res1 = await mockReq('FirstQuery').execute(rnl);
expect(res1.data).toBe('PAYLOAD');
expect(fetchMock.calls('/graphql')).toHaveLength(1);

await sleep(20);

// data from cache
const res2 = await mockReq('FirstQuery').execute(rnl);
expect(res2.data).toBe('PAYLOAD');
expect(fetchMock.calls('/graphql')).toHaveLength(1);

await sleep(20);

// data from cache 40ms after 30ms initial cache
const res3 = await mockReq('FirstQuery').execute(rnl);
expect(res3.data).toBe('PAYLOAD');
expect(fetchMock.calls('/graphql')).toHaveLength(1);
});
});
17 changes: 15 additions & 2 deletions src/middlewares/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,20 @@ type CacheMiddlewareOpts = {|
allowFormData?: boolean,
clearOnMutation?: boolean,
cacheErrors?: boolean,
updateTTLOnGet?: boolean,
|};

export default function cacheMiddleware(opts?: CacheMiddlewareOpts): Middleware {
const { size, ttl, onInit, allowMutations, allowFormData, clearOnMutation, cacheErrors } =
opts || {};
const {
size,
ttl,
onInit,
allowMutations,
allowFormData,
clearOnMutation,
cacheErrors,
updateTTLOnGet,
} = opts || {};
const cache = new QueryResponseCache({
size: size || 100, // 100 requests
ttl: ttl || 15 * 60 * 1000, // 15 minutes
Expand Down Expand Up @@ -57,6 +66,10 @@ export default function cacheMiddleware(opts?: CacheMiddlewareOpts): Middleware

const cachedRes = cache.get(queryId, variables);
if (cachedRes) {
if (updateTTLOnGet) {
cache.set(queryId, variables, cachedRes);
}

return cachedRes;
}

Expand Down

0 comments on commit 333a1c3

Please sign in to comment.