Skip to content

Commit

Permalink
fix: aborted requests do not clear its cache afterwards if previous r…
Browse files Browse the repository at this point in the history
…equest was cached (#922)
  • Loading branch information
Wykks committed Oct 18, 2024
1 parent a7a4e31 commit c75b493
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/interceptors/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,15 @@ export function defaultResponseInterceptor(axios: AxiosCacheInstance): ResponseI
*
* Also update the waiting list for this key by rejecting it.
*/
const rejectResponse = async (responseId: string, config: CacheRequestConfig) => {
const rejectResponse = async (
responseId: string,
config: CacheRequestConfig,
clearCache = true
) => {
// Updates the cache to empty to prevent infinite loading state
await axios.storage.remove(responseId, config);
if (clearCache) {
await axios.storage.remove(responseId, config);
}

// Rejects the deferred, if present
const deferred = axios.waiting.get(responseId);
Expand Down Expand Up @@ -297,7 +303,11 @@ export function defaultResponseInterceptor(axios: AxiosCacheInstance): ResponseI
}

// Rejects all other requests waiting for this response
await rejectResponse(id, config);
await rejectResponse(
id,
config,
error.code !== 'ERR_CANCELED' || (error.code === 'ERR_CANCELED' && cache.state !== 'cached')
);

throw error;
}
Expand Down
29 changes: 29 additions & 0 deletions test/interceptors/response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -361,4 +361,33 @@ describe('Response Interceptor', () => {
assert.equal(storage.state, 'cached');
assert.equal(storage.data?.data, true);
});

// https://github.com/arthurfiorette/axios-cache-interceptor/issues/922
it('Aborted requests do not clear its cache afterwards if previous request was cached', async () => {
const axios = mockAxios();

const id = '1';

// first request
await axios.get('url', { id });

// Second request cancelled
const controller = new AbortController();
const cancelled = axios.get('url', { id, signal: controller.signal });
controller.abort();
try {
await cancelled;
assert.fail('should have thrown an error');
} catch (error: any) {
assert.equal(error.code, 'ERR_CANCELED');
}

// Third request
const promise = axios.get('url', { id });

const response = await promise;

// Third request should still have cached data
await assert.equal(response.cached, true);
});
});

0 comments on commit c75b493

Please sign in to comment.