Skip to content

Commit

Permalink
add cacheKeyGenerator option
Browse files Browse the repository at this point in the history
  • Loading branch information
shrpne committed Jul 18, 2023
1 parent f4da8f3 commit 940af6f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
21 changes: 21 additions & 0 deletions src/__tests__/test-cacheAdapterEnhancer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,24 @@ test('use a custom cache with request individual config', async t => {

t.is(adapterCb.callCount, 3);
});

test('custom cache key will produce two different requests', async t => {

const adapterCb = spy();
const mockedAdapter = genMockAdapter(adapterCb);
const http = axios.create({
adapter: cacheAdapterEnhancer(mockedAdapter, {
cacheKeyGenerator(config, defaultCacheKey) {
return defaultCacheKey + (config.headers?.Authorization || '');
},
}),
});

const onSuccess = spy();
await http.get('/users', { headers: { Authorization: 'test1' } }).then(onSuccess);
await http.get('/users', { headers: { Authorization: 'test1' } }).then(onSuccess);
await http.get('/users', { headers: { Authorization: 'test2' } }).then(onSuccess);
t.is(adapterCb.callCount, 2);
t.is(onSuccess.callCount, 3);

});
9 changes: 7 additions & 2 deletions src/cacheAdapterEnhancer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @since 2017-10-12
*/

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

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

// build the index according to the url and params
const index = buildSortedURL(url, params, paramsSerializer);
const defaultCacheKey = buildSortedURL(url, params, paramsSerializer);
// if had provided key generator, then use it to produce custom key
const customCacheKey = options.cacheKeyGenerator && options.cacheKeyGenerator(config, defaultCacheKey);

const index = customCacheKey || defaultCacheKey;

let responsePromise = cache.get(index);

Expand Down

0 comments on commit 940af6f

Please sign in to comment.