Skip to content

Commit

Permalink
feat(cacheMiddleware): add clearOnMutation option (thanks @haruska)
Browse files Browse the repository at this point in the history
* update cache to optionally clear on mutation

* add option to readme
  • Loading branch information
haruska authored and nodkz committed Mar 15, 2018
1 parent 15bdcb8 commit 0071220
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 9 additions & 3 deletions src/middlewares/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand Down

0 comments on commit 0071220

Please sign in to comment.