fix: transformResponse running twice on cached requests (#775)

This commit is contained in:
Amrendra Kumar 2024-01-18 21:54:44 -05:00 committed by GitHub
parent ed99d775bb
commit 0214ec682c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 34 additions and 4 deletions

View File

@ -219,6 +219,11 @@ export function defaultRequestInterceptor(axios: AxiosCacheInstance) {
cachedResponse = cache.data;
}
// The cached data is already transformed after receiving the response from the server.
// Reapplying the transformation on the transformed data will have an unintended effect.
// Since the cached data is already in the desired format, there is no need to apply the transformation function again.
config.transformResponse = undefined;
// Even though the response interceptor receives this one from here,
// it has been configured to ignore cached responses = true
config.adapter = function cachedAdapter(): Promise<CacheAxiosResponse> {

View File

@ -354,6 +354,25 @@ describe('Request Interceptor', () => {
assert.equal(headers2[Header.Expires], undefined);
});
it('ensure cached data is not transformed', async () => {
const axios = mockAxios();
// data will transformed with first request
const res1 = await axios.get('url', {
transformResponse: (data: unknown) => [data]
});
assert.notEqual(res1.config.transformResponse, undefined);
// cached data should not transform the data as it is alread in desired format.
// transform function is nullified in this scenario
const res2 = await axios.get('url', {
transformResponse: (data: unknown) => [data]
});
assert.equal(res2.config.transformResponse, undefined);
});
it('ensures request with urls in exclude.paths are not cached', async () => {
const axios = mockAxios({
cachePredicate: {

View File

@ -273,13 +273,19 @@ describe('Response Interceptor', () => {
it('Works when modifying response', async () => {
const axios = mockAxios();
const normal = await axios.get('url');
const transformed = await axios.get('url', {
// fresh response from server and transformed
const freshResponse = await axios.get('url', {
transformResponse: (data: unknown) => [data]
});
assert.ok(normal.data);
assert.deepEqual(transformed.data, [true]);
// cached response
// should not transform again as already in desired format
const cachedResponse = await axios.get('url', {
transformResponse: (data: unknown) => [data]
});
assert.deepEqual(freshResponse.data, [true]);
assert.deepEqual(cachedResponse.data, [true]);
});
it('Works when modifying the error response', async () => {