From 007122062fc9d4761ec38c15f00aa10bf0488fd5 Mon Sep 17 00:00:00 2001 From: Jason Haruska Date: Thu, 15 Mar 2018 09:24:41 -0500 Subject: [PATCH] feat(cacheMiddleware): add `clearOnMutation` option (thanks @haruska) * update cache to optionally clear on mutation * add option to readme --- README.md | 1 + src/middlewares/cache.js | 12 +++++++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1028b23..0d885e7 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ Middlewares - `onInit` - function(cache) which will be called once when cache is created. As first argument you receive `QueryResponseCache` instance from `relay-runtime`. - `allowMutations` - allow to cache Mutation requests (default: `false`) - `allowFormData` - allow to cache FormData requests (default: `false`) + - `clearOnMutation` - clear the cache on any Mutation (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. diff --git a/src/middlewares/cache.js b/src/middlewares/cache.js index 1b9bfb7..96a377b 100644 --- a/src/middlewares/cache.js +++ b/src/middlewares/cache.js @@ -10,10 +10,11 @@ type CacheMiddlewareOpts = {| onInit?: (cache: QueryResponseCache) => any, allowMutations?: boolean, allowFormData?: boolean, + clearOnMutation?: boolean, |}; export default function queryMiddleware(opts?: CacheMiddlewareOpts): Middleware { - const { size, ttl, onInit, allowMutations, allowFormData } = opts || {}; + const { size, ttl, onInit, allowMutations, allowFormData, clearOnMutation } = opts || {}; const cache = new QueryResponseCache({ size: size || 100, // 100 requests ttl: ttl || 15 * 60 * 1000, // 15 minutes @@ -24,8 +25,13 @@ export default function queryMiddleware(opts?: CacheMiddlewareOpts): Middleware } return next => async req => { - if (req.isMutation() && !allowMutations) { - return next(req); + if (req.isMutation()) { + if (clearOnMutation) { + cache.clear(); + } + if (!allowMutations) { + return next(req); + } } if (req.isFormData() && !allowFormData) {