fetch-intercept icon indicating copy to clipboard operation
fetch-intercept copied to clipboard

Request interceptor containing an async call

Open stokedout opened this issue 6 years ago • 3 comments

Hi, Is it possible to perform asynchronous calls in a "request" interceptor? I have an interceptor that gets the access token from the localforage library but all methods are asynchronous. If so could you provide a code example please? Thanks

stokedout avatar Feb 25 '19 16:02 stokedout

You might have realized this already but it already works this way:

this.unregisterFetch = fetchIntercept.register({
  request: async (url, config = {}) => {
    const fetchOptions = {
      ...config,
    };

    try {
      const token = await this.Authenticator.getIdToken();

      if (!fetchOptions.headers) {
        fetchOptions.headers = new Headers();
      }
      fetchOptions.headers.append('Authorization', `Bearer ${token}`);
    } catch (error) {
      // Should we re-login or inspect error here?
    }

    return [url, fetchOptions];
  },
});

If you're using something like adal/angular-adal note that my getIdToken is just a wrapper around their ridiculous synchronous/callback call that promisifies it.

Vassi avatar May 15 '19 17:05 Vassi

You might have realized this already but it already works this way:

this.unregisterFetch = fetchIntercept.register({
  request: async (url, config = {}) => {
    const fetchOptions = {
      ...config,
    };

    try {
      const token = await this.Authenticator.getIdToken();

      if (!fetchOptions.headers) {
        fetchOptions.headers = new Headers();
      }
      fetchOptions.headers.append('Authorization', `Bearer ${token}`);
    } catch (error) {
      // Should we re-login or inspect error here?
    }

    return [url, fetchOptions];
  },
});

If you're using something like adal/angular-adal note that my getIdToken is just a wrapper around their ridiculous synchronous/callback call that promisifies it.

This way does not take effect

Ray0401 avatar Sep 23 '21 12:09 Ray0401

Hi, Is it possible to perform asynchronous calls in a "request" interceptor? I have an interceptor that gets the access token from the localforage library but all methods are asynchronous. If so could you provide a code example please? Thanks

I have the same issue

Ray0401 avatar Sep 23 '21 12:09 Ray0401