I have an api client in my application with some interceptors:
const api = new OpenAPIClientAxios({...})
const client = api.initSync()
client.interceptors.request.use(...)
client.interceptors.response.use(...)
I want to write a request interceptor that will check for some data in local storage. If the data is present, I would like to not make a request at all, rather, simply respond with the local storage data.
Is this possible? Or am I misusing interceptors?
3
Answers
Interceptors can only be used to manipulate the configuration of requests and responses. Unfortunately, you cannot bypass a request entirely with them.
Axios does provide an
adapter
config which…Using this, you can create an Axios instance with a custom
adapter
to intercept requests and provide responses using local data.Answering the question..
As for my understanding, it is POSSIBLE. The idea here is to use a request interceptor to check if the required data exists in the local storage. If it does, then return a resolved promise with the local storage data, effectively bypassing the API request. If the data does not exist in the local storage, you can proceed with the API request as usual.
Example execution.
This approach allows you to cache data in local storage and use it to respond to API requests, reducing the number of requests made to the server and improving performance. But, it’s important to remember that local storage has its limitations, including storage capacity and security risks. Always check that you are handling data securely and appropriately.
I’d like to propose another approach: instead of adding an interceptor to axios, you could write a function that abstract the retrieval of the data and that would:
In other words, write a domain service / repository.