mirror of
https://github.com/arthurfiorette/axios-cache-interceptor.git
synced 2025-12-08 17:36:16 +00:00
perf: only execute one generateKey per request
This commit is contained in:
parent
6f9ef36e75
commit
fa2c6e3204
@ -26,7 +26,7 @@ export function defaultRequestInterceptor(axios: AxiosCacheInstance) {
|
||||
return config;
|
||||
}
|
||||
|
||||
const key = axios.generateKey(config);
|
||||
const key = (config.id = axios.generateKey(config));
|
||||
|
||||
// Assumes that the storage handled staled responses
|
||||
let cache = await axios.storage.get(key);
|
||||
|
||||
@ -27,7 +27,7 @@ export function defaultResponseInterceptor(
|
||||
};
|
||||
|
||||
const onFulfilled: ResponseInterceptor['onFulfilled'] = async (response) => {
|
||||
response.id ??= axios.generateKey(response.config);
|
||||
response.id = response.config.id ??= axios.generateKey(response.config);
|
||||
response.cached ??= false;
|
||||
|
||||
// Response is already cached
|
||||
|
||||
@ -117,14 +117,36 @@ describe('test request interceptor', () => {
|
||||
it("expect two requests with different body aren't cached", async () => {
|
||||
const axios = mockAxios();
|
||||
|
||||
const url = 'https://jsonplaceholder.typicode.com/posts';
|
||||
|
||||
const result = await axios.get(url, { data: { a: 1 } });
|
||||
const result = await axios.get('url', { data: { a: 1 } });
|
||||
|
||||
expect(result.cached).toBe(false);
|
||||
|
||||
const result2 = await axios.get(url, { data: { a: 2 } });
|
||||
const result2 = await axios.get('url', { data: { a: 2 } });
|
||||
|
||||
expect(result2.cached).toBe(false);
|
||||
});
|
||||
|
||||
it('tests a request with really long keys', async () => {
|
||||
const axios = mockAxios();
|
||||
|
||||
const result = await axios.get('url', {
|
||||
data: Array(5e3).fill({ rnd: Math.random() }),
|
||||
params: Array(5e3).fill({ rnd: Math.random() })
|
||||
});
|
||||
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
|
||||
it('expect keyGenerator is called once during a single request', async () => {
|
||||
const axios = mockAxios();
|
||||
|
||||
const spy = jest.spyOn(axios, 'generateKey');
|
||||
|
||||
await axios.get('url', {
|
||||
// generates a long key
|
||||
data: Array(5e3).fill({ rnd: Math.random() })
|
||||
});
|
||||
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user