fredrik.hjarner
fredrik.hjarner

Reputation: 720

Delay all requests with interceptor

For debugging purposes I want to delay all requests so that I can simulate that it actually takes time to load resources. I guess that this can be done in a interceptor somehow.

I do manage to delay single requests now with:

const delay =
    milliseconds =>
      new Promise(resolve =>
        setTimeout(resolve, milliseconds));

delay(1000)
  .then(() => {
    axios.post(
      ...
    ).then((response) => {
      ...
    });
  });

But I would be more nice to do it for all requests at one place.

Upvotes: 3

Views: 9362

Answers (1)

RWAM
RWAM

Reputation: 7018

Sorry for the late response, but I've had a similar issue. I'd like to use an artificial delay for almost all requests to improve usability and for debugging purposes too. I've created a new service (situated at src/services/HttpClient.js) and use a global request interceptor:

import axios from 'axios';

// Create a new instance.
const service = axios.create({
  baseURL: process.env.API_ENDPOINT,
  delayed: true  // use this custom option to allow overrides
});

service.interceptors.request.use((config) =>
  if (config.delayed) {
    return new Promise(resolve => setTimeout(() => resolve(config), 600));
  }
  return config;
});

export default service;

The custom config option delayed can be used to override the global behavior. The following request will be performed without a delay:

import $http from '@/services/HttpClient';

$http.get('/example-url', {
  delayed: false
}).then((response) {
  …
});

Requests in the background don't use a delay in my app. But all requests triggered by an action by the user use the delay.

Upvotes: 12

Related Questions