From 940af6f4ba7919ee794d87c8698e3e490dad5bbf Mon Sep 17 00:00:00 2001 From: shrpne Date: Wed, 23 Nov 2022 18:18:37 +0300 Subject: [PATCH] add cacheKeyGenerator option --- src/__tests__/test-cacheAdapterEnhancer.ts | 21 +++++++++++++++++++++ src/cacheAdapterEnhancer.ts | 9 +++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/__tests__/test-cacheAdapterEnhancer.ts b/src/__tests__/test-cacheAdapterEnhancer.ts index 42d9e66..639d58f 100644 --- a/src/__tests__/test-cacheAdapterEnhancer.ts +++ b/src/__tests__/test-cacheAdapterEnhancer.ts @@ -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); + +}); diff --git a/src/cacheAdapterEnhancer.ts b/src/cacheAdapterEnhancer.ts index b9d7629..b2a266d 100644 --- a/src/cacheAdapterEnhancer.ts +++ b/src/cacheAdapterEnhancer.ts @@ -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'; @@ -23,6 +23,7 @@ export type Options = { enabledByDefault?: boolean, cacheFlag?: string, defaultCache?: ICacheLike, + cacheKeyGenerator?: (config: AxiosRequestConfig, defaultCacheKey: string) => string, }; export default function cacheAdapterEnhancer(adapter: AxiosAdapter, options: Options = {}): AxiosAdapter { @@ -46,7 +47,11 @@ export default function cacheAdapterEnhancer(adapter: AxiosAdapter, options: Opt const cache: ICacheLike = 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);