Skip to content

Commit 0071220

Browse files
haruskanodkz
authored andcommitted
feat(cacheMiddleware): add clearOnMutation option (thanks @haruska)
* update cache to optionally clear on mutation * add option to readme
1 parent 15bdcb8 commit 0071220

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ Middlewares
7171
- `onInit` - function(cache) which will be called once when cache is created. As first argument you receive `QueryResponseCache` instance from `relay-runtime`.
7272
- `allowMutations` - allow to cache Mutation requests (default: `false`)
7373
- `allowFormData` - allow to cache FormData requests (default: `false`)
74+
- `clearOnMutation` - clear the cache on any Mutation (default: `false`)
7475
- **authMiddleware** - for adding auth token, and refreshing it if gets 401 response from server.
7576
- `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).
7677
- `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.

src/middlewares/cache.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,11 @@ type CacheMiddlewareOpts = {|
1010
onInit?: (cache: QueryResponseCache) => any,
1111
allowMutations?: boolean,
1212
allowFormData?: boolean,
13+
clearOnMutation?: boolean,
1314
|};
1415

1516
export default function queryMiddleware(opts?: CacheMiddlewareOpts): Middleware {
16-
const { size, ttl, onInit, allowMutations, allowFormData } = opts || {};
17+
const { size, ttl, onInit, allowMutations, allowFormData, clearOnMutation } = opts || {};
1718
const cache = new QueryResponseCache({
1819
size: size || 100, // 100 requests
1920
ttl: ttl || 15 * 60 * 1000, // 15 minutes
@@ -24,8 +25,13 @@ export default function queryMiddleware(opts?: CacheMiddlewareOpts): Middleware
2425
}
2526

2627
return next => async req => {
27-
if (req.isMutation() && !allowMutations) {
28-
return next(req);
28+
if (req.isMutation()) {
29+
if (clearOnMutation) {
30+
cache.clear();
31+
}
32+
if (!allowMutations) {
33+
return next(req);
34+
}
2935
}
3036

3137
if (req.isFormData() && !allowFormData) {

0 commit comments

Comments
 (0)