87Implement request and response interceptors similar to Axios
Problem
Implement createHttpClient({ baseURL = "", fetch: fetchImpl = window.fetch }), a small Axios-style client on top of fetch:
client.request(config), whereconfigis{ url, method = "GET", headers = {}, data }, plus shortcutsclient.get(url, config)andclient.post(url, data, config).- Requests go to
baseURL + url.datais sent as JSON withcontent-type: application/json. - The result is
{ data, status, headers, config }, wheredatais parsed JSON (or text if the body is not JSON). - A status outside 200–299 rejects with an
Errorthat haserror.response(the same shape) anderror.config. client.interceptors.request.use(onFulfilled, onRejected)andclient.interceptors.response.use(onFulfilled, onRejected)register interceptors and return an id;.eject(id)removes one.
Order, like Axios: request interceptors run in reverse order of registration (the last one added runs first), response interceptors in registration order. Each may return a value or a promise. A response onRejected can recover, for example by refreshing a token and returning client.request(error.config).
const api = createHttpClient({ baseURL: "https://api.example.com" });
api.interceptors.request.use((config) => ({ ...config, headers: { ...config.headers, authorization: `Bearer ${getToken()}` } }));
api.interceptors.response.use(undefined, async (error) => {
if (error.response?.status === 401 && !error.config.retried) {
await refreshToken();
return api.request({ ...error.config, retried: true });
}
throw error;
});
const { data } = await api.get("/me");Try it yourself
Write your solution, run it, then submit to check it against the tests.
Step-by-step
Each manager stores { id, onFulfilled, onRejected } entries in an array, with use returning a new id and eject(id) removing that entry. Keep removed entries out of future chains only.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.