Created
August 22, 2020 18:02
-
-
Save pakman198/befaad5b472a2fd09234bd059c791eae to your computer and use it in GitHub Desktop.
axios interceptors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
export const experimentsInterceptor = () => { | |
const getExperiments = () => { | |
const [, params] = window.location.search.split('?'); | |
const experiments = params.split('ex.'); | |
const values = experiments.reduce((tally, item) => { | |
if (item.match(/^[A-Z][A-Z][A-Z]\d\d/)) { | |
const newItem = item.replace('&', ''); | |
tally.push(newItem); | |
} | |
return tally; | |
}, []); | |
const set = new Set(values); | |
return [...set]; | |
}; | |
axios.interceptors.request.use( | |
config => { | |
const experiments = getExperiments(); | |
if (experiments.length !== 0) { | |
config.headers['my-custom-header'] = experiments.join(','); | |
} | |
return config; | |
}, | |
error => { | |
// Do something with request error | |
return Promise.reject(error); | |
} | |
); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import axiosMock from 'jest-mock-axios'; | |
describe('experimentInterceptor', () => { | |
const BASE_URL_WITH_PARAMS = 'http://localhost:3000/some_route/child_route?q=something&ex.RGB00=2&ex.ABC99=3'; | |
const API_ENDPOINT = 'http://localhost:9000/some_route'; | |
beforeEach(() => { | |
axiosMock.reset(); | |
}); | |
it('should add my-custom-header header to any api request when the URL has experiment params', async () => { | |
mockWindow(BASE_URL_WITH_PARAMS); | |
experimentsInterceptor(); | |
axiosMock.get(API_ENDPOINT); | |
const config = await axios.interceptors.request.handlers[0].fulfilled({ | |
url: API_ENDPOINT, | |
headers: {} | |
}); | |
expect(config.headers).toEqual({ | |
'my-custom-header': 'RGB00=2,ABC99=3' | |
}); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mockWindow = search => { | |
Object.defineProperty(global, 'window', { | |
value: { | |
location: { | |
search | |
} | |
}, | |
writable: true | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment