Skip to content

Commit aa80985

Browse files
committed
add cacheKeyGenerator option
1 parent f4da8f3 commit aa80985

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/__tests__/test-cacheAdapterEnhancer.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,24 @@ test('use a custom cache with request individual config', async t => {
160160

161161
t.is(adapterCb.callCount, 3);
162162
});
163+
164+
test('custom cache key will produce two different requests', async t => {
165+
166+
const adapterCb = spy();
167+
const mockedAdapter = genMockAdapter(adapterCb);
168+
const http = axios.create({
169+
adapter: cacheAdapterEnhancer(mockedAdapter, {
170+
cacheKeyGenerator(config, defaultCacheKey) {
171+
return defaultCacheKey + config.headers.Authorization;
172+
},
173+
}),
174+
});
175+
176+
const onSuccess = spy();
177+
await http.get('/users', { headers: { Authorization: 'test1' } }).then(onSuccess);
178+
await http.get('/users', { headers: { Authorization: 'test1' } }).then(onSuccess);
179+
await http.get('/users', { headers: { Authorization: 'test2' } }).then(onSuccess);
180+
t.is(adapterCb.callCount, 2);
181+
t.is(onSuccess.callCount, 3);
182+
183+
});

src/cacheAdapterEnhancer.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* @since 2017-10-12
55
*/
66

7-
import { AxiosAdapter, AxiosPromise } from 'axios';
7+
import { AxiosAdapter, AxiosPromise, AxiosRequestConfig } from 'axios';
88
import LRUCache from 'lru-cache';
99
import buildSortedURL from './utils/buildSortedURL';
1010
import isCacheLike, { ICacheLike } from './utils/isCacheLike';
@@ -23,6 +23,7 @@ export type Options = {
2323
enabledByDefault?: boolean,
2424
cacheFlag?: string,
2525
defaultCache?: ICacheLike<AxiosPromise>,
26+
cacheKeyGenerator?: (config: AxiosRequestConfig, defaultCacheKey: string) => string,
2627
};
2728

2829
export default function cacheAdapterEnhancer(adapter: AxiosAdapter, options: Options = {}): AxiosAdapter {
@@ -46,7 +47,11 @@ export default function cacheAdapterEnhancer(adapter: AxiosAdapter, options: Opt
4647
const cache: ICacheLike<AxiosPromise> = isCacheLike(useCache) ? useCache : defaultCache;
4748

4849
// build the index according to the url and params
49-
const index = buildSortedURL(url, params, paramsSerializer);
50+
const defaultCacheKey = buildSortedURL(url, params, paramsSerializer);
51+
// if had provided key generator, then use it to produce custom key
52+
const customCacheKey = options.cacheKeyGenerator && options.cacheKeyGenerator(config, defaultCacheKey);
53+
54+
const index = customCacheKey || defaultCacheKey;
5055

5156
let responsePromise = cache.get(index);
5257

0 commit comments

Comments
 (0)