Skip to content

Commit

Permalink
perf: only execute one generateKey per request
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette committed Jan 14, 2022
1 parent 6f9ef36 commit fa2c6e3
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/interceptors/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/interceptors/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 26 additions & 4 deletions test/interceptors/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit fa2c6e3

Please sign in to comment.