UNPKG

1.65 kBJavaScriptView Raw
1'use strict';
2
3const createArgErrorMessageProd = require('../private/createArgErrorMessageProd');
4const Cache = require('./Cache');
5const cacheEntryPrune = require('./cacheEntryPrune');
6
7/**
8 * Prunes [cache]{@link Cache#store} entries. Useful after a mutation.
9 * @kind function
10 * @name cachePrune
11 * @param {Cache} cache Cache to update.
12 * @param {CacheKeyMatcher} [cacheKeyMatcher] Matches [cache keys]{@link CacheKey} to prune. By default all are matched.
13 * @fires Cache#event:prune
14 * @fires Cache#event:delete
15 * @example <caption>Ways to `import`.</caption>
16 * ```js
17 * import { cachePrune } from 'graphql-react';
18 * ```
19 *
20 * ```js
21 * import cachePrune from 'graphql-react/public/cachePrune.js';
22 * ```
23 * @example <caption>Ways to `require`.</caption>
24 * ```js
25 * const { cachePrune } = require('graphql-react');
26 * ```
27 *
28 * ```js
29 * const cachePrune = require('graphql-react/public/cachePrune');
30 * ```
31 */
32module.exports = function cachePrune(cache, cacheKeyMatcher) {
33 if (!(cache instanceof Cache))
34 throw new TypeError(
35 typeof process === 'object' && process.env.NODE_ENV !== 'production'
36 ? 'Argument 1 `cache` must be a `Cache` instance.'
37 : createArgErrorMessageProd(1)
38 );
39
40 if (cacheKeyMatcher !== undefined && typeof cacheKeyMatcher !== 'function')
41 throw new TypeError(
42 typeof process === 'object' && process.env.NODE_ENV !== 'production'
43 ? 'Argument 2 `cacheKeyMatcher` must be a function.'
44 : createArgErrorMessageProd(2)
45 );
46
47 for (const cacheKey in cache.store)
48 if (!cacheKeyMatcher || cacheKeyMatcher(cacheKey))
49 cacheEntryPrune(cache, cacheKey);
50};