perf: only execute one generateKey per request

This commit is contained in:
arthurfiorette 2022-01-13 21:23:36 -03:00
parent 6f9ef36e75
commit fa2c6e3204
No known key found for this signature in database
GPG Key ID: 9D190CD53C53C555
3 changed files with 28 additions and 6 deletions

View File

@ -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);

View File

@ -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

View File

@ -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);
});
});