skip to Main Content

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


  1. 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…

    allows custom handling of requests

    Using this, you can create an Axios instance with a custom adapter to intercept requests and provide responses using local data.

    // mock localStorage
    const localStorage = {s:{},setItem(k,v){this.s[k]=v},getItem(k){return this.s[k]??null}};
    // mock OpenAPI client
    const client = /* api.initSync() */ axios.create({ baseURL: "https://jsonplaceholder.typicode.com/" });
    
    const wrapper = axios.create({
      adapter: ({ adapter, ...config }) => {
        const data = JSON.parse(localStorage.getItem("data"));
        if (data) {
          // return a valid response
          return Promise.resolve({
            data,
            config,
            status: 200,
          });
        }
        
        // otherwise pass-through to the real client
        return client(config);
      }
    });
    
    (async () => {
      // with no data present
      console.log("no local data:", (await wrapper.get("/todos/1")).data);
    
      // with local data
      localStorage.setItem("data", JSON.stringify({ foo: "FOO" }));
      console.log("with local data:", (await wrapper.get("/todos/1")).data);
    })();
    .as-console-wrapper { max-height: 100% !important; }
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
    Login or Signup to reply.
  2. Answering the question..

    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?

    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.

    const api = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com/' });
    api.interceptors.request.use((config) => {
     // Check for data in local storage
        const data = localStorage.getItem('posts');
        // If data is present, return a response with that data
        if (data) {
            return Promise.resolve({ data: JSON.parse(data) });
        }
        // If data is not present, continue with the request
            return config;
    }, (error) => {
    // Handle request error
        return Promise.reject(error);
    });
    api.get('/posts')
    .then((response) => {
        console.log(response.data[0]);
    })
    .catch((error) => {
        console.error(error);
    });
    

    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.

    Login or Signup to reply.
  3. 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:

    • Check the local data and return the found data if any
    • Execute the remote call otherwise

    In other words, write a domain service / repository.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search