Skip to content

Commit 8ee5e0e

Browse files
committed
feat(useApi): add shouldUseApiCache to enable/disable the particular requests
1 parent 231df9d commit 8ee5e0e

File tree

5 files changed

+74
-20
lines changed

5 files changed

+74
-20
lines changed

README.md

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -299,17 +299,18 @@ export const render = async (req, axios) => {
299299

300300
_Each property is optional_
301301

302-
| Name | Type | Default | Description |
303-
| -------------- | ----------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------- |
304-
| cache | LRU<String, ReactUseApi.CacheData \| any> | new LRU() | The cache instance based on lru-cache |
305-
| axios | AxiosStatic \| AxiosInstance | axios | axios instance (http client) |
306-
| maxRequests | number | 50 | The maximum of API requests when SSR |
307-
| autoPurgeCache | boolean | true | Cache data will be cleaned up after executing loadApiCache() |
308-
| useCacheData | boolean | true | Set true to inject JS cache data into html when calling injectSSRHtml() |
309-
| renderSSR | Function | () => '' | A callback to render SSR string for injectSSRHtml() |
310-
| isSSR | Function | () => typeof window === 'undefined' | A function to determine if the current environment is server |
311-
| debug | boolean | true | Set true to get debug message from console |
312-
| clientCacheVar | string | 'USE_API_CACHE' | The JS variable name of cache data |
302+
| Name | Type | Default | Description |
303+
| ----------------- | ----------------------------------------- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
304+
| cache | LRU<String, ReactUseApi.CacheData \| any> | new LRU() | The cache instance based on lru-cache |
305+
| axios | AxiosStatic \| AxiosInstance | axios | axios instance (http client) |
306+
| maxRequests | number | 50 | The maximum of API requests when SSR |
307+
| autoPurgeCache | boolean | true | Cache data will be cleaned up after executing `loadApiCache()` |
308+
| useCacheData | boolean | true | Set true to inject JS cache data into html when calling `injectSSRHtml()` |
309+
| debug | boolean | true | Set true to get debug message from console |
310+
| clientCacheVar | string | 'USE_API_CACHE' | The JS variable name of cache data |
311+
| renderSSR | Function | () => '' | A callback to render SSR string for injectSSRHtml() |
312+
| isSSR | Function | () => typeof window === 'undefined' | A function to determine if the current environment is server |
313+
| shouldUseApiCache | Function | (config?: ReactUseApi.Config, cacheKey?: string): boolean | Returns true to enable useApi to get the API data from API cache, which is loaded by `loadApiCache`. Default is true |
313314

314315
#### Arguments of injectSSRHtml
315316

src/__tests__/common.test.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,11 @@ describe('configure tests', () => {
5656
axios: axios.create(),
5757
cache: new LRU<string, ReactUseApi.CacheData>(),
5858
maxRequests: 100,
59+
useCacheData: false,
60+
deleteAfterLoading: false,
5961
renderSSR: () => '',
6062
isSSR: () => true,
61-
useCacheData: false,
62-
deleteAfterLoading: false
63+
shouldUseApiCache: () => false
6364
},
6465
collection: {
6566
ssrConfigs: customSSRConfig,
@@ -172,6 +173,7 @@ describe('getResponseData tests', () => {
172173
headers: {}
173174
},
174175
loading: false,
176+
fromCache: false,
175177
$cacheKey: 'foo/bar'
176178
}
177179
const returnedData = getResponseData(options, state)
@@ -219,6 +221,7 @@ describe('getResponseData tests', () => {
219221
}
220222
],
221223
loading: false,
224+
fromCache: false,
222225
$cacheKey: 'foo/bar'
223226
}
224227
const returnedData = getResponseData(options, state)

src/__tests__/useApi.test.tsx

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,6 @@ describe('useApi tests', () => {
160160
it('should work well with cache data', async () => {
161161
console.log = jest.fn()
162162
const cache = new LRU<string, ReactUseApi.CacheData | any>()
163-
const originalDel = cache.del
164-
jest.spyOn(cache, 'del').mockImplementation(originalDel)
165163
const context = {
166164
settings: {
167165
cache,
@@ -541,6 +539,54 @@ describe('useApi tests', () => {
541539
spy.mockRestore()
542540
})
543541

542+
it('should shouldUseApiCache work well', async () => {
543+
console.log = jest.fn()
544+
const cache = new LRU<string, ReactUseApi.CacheData | any>()
545+
const context = {
546+
settings: {
547+
cache,
548+
debug: true,
549+
isSSR: () => false,
550+
shouldUseApiCache: (config, cacheKey) => {
551+
if (cacheKey.includes('/no/cache')) {
552+
return false
553+
}
554+
return true
555+
}
556+
}
557+
} as ReactUseApi.CustomContext
558+
const cacheKey = '{"url":"/api/v1/foo/bar"}'
559+
cache.set(cacheKey, {
560+
response: {
561+
data: apiData
562+
}
563+
})
564+
const noCacheData = {
565+
no: 'dont touch me'
566+
}
567+
const noCacheApiUrl = '/api/v1/no/cache'
568+
cache.set(`{"url":"${noCacheApiUrl}"}`, {
569+
response: {
570+
data: noCacheData
571+
}
572+
})
573+
const wrapper = createWrapper(context)
574+
const { result, rerender } = renderHook(
575+
() => {
576+
const [data1] = useApi(url)
577+
const [data2] = useApi(noCacheApiUrl)
578+
return [data1, data2]
579+
},
580+
{ wrapper }
581+
)
582+
// cannot use waitForNextUpdate to test the non-rerender situation, use rerender instead
583+
rerender()
584+
585+
const [data1, data2] = result.current
586+
expect(data1).toEqual(apiData)
587+
expect(data2).not.toEqual(noCacheData)
588+
})
589+
544590
it('should watch work well', async () => {
545591
const wrapper = createWrapper({
546592
settings: {

src/common.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,14 @@ export const defaultSettings = {
88
maxRequests: 50,
99
autoPurgeCache: true,
1010
useCacheData: true,
11-
renderSSR: (() => '') as (...args: any[]) => string,
12-
isSSR: (() => typeof window === 'undefined') as (...args: any[]) => boolean,
1311
debug: false,
14-
clientCacheVar: '__USE_API_CACHE__'
12+
clientCacheVar: '__USE_API_CACHE__',
13+
isSSR: (...args: any[]): boolean | void => typeof window === 'undefined',
14+
renderSSR: (...args: any[]): string => '',
15+
shouldUseApiCache: (
16+
config?: ReactUseApi.Config,
17+
cacheKey?: string
18+
): boolean | void => true
1519
}
1620
export const ACTIONS = {
1721
REQUEST_START: 'REQUEST_START',

src/useApi.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export const useApi = (
3131
invariant(verifyConfig(config), `API config "${rawConfig}" is invalid.`)
3232
const context = useContext(ApiContext)
3333
const {
34-
settings: { cache, debug },
34+
settings: { cache, debug, shouldUseApiCache },
3535
isSSR,
3636
collection: { ssrConfigs, cacheKeys }
3737
} = context
@@ -48,7 +48,7 @@ export const useApi = (
4848
const { current: refData } = ref
4949
const cacheData: ReactUseApi.CacheData = cache.get(cacheKey)
5050
let defaultState = { ...initState }
51-
if (cacheData) {
51+
if (cacheData && (isSSR || !!shouldUseApiCache(config, cacheKey))) {
5252
const { response, error } = cacheData
5353
const action = {
5454
type: ACTIONS.REQUEST_END,

0 commit comments

Comments
 (0)