r/programminghelp • • Mar 02 '20

Other Stuck with JS Axios request interceptors

I'm building a NodeJS tool that calls an API which requires token authentication. The tool itself is for monitoring directory sizes in a cloud-based storage system, and querying a directory size requires a few steps:

  • Ask the API to refresh its info on the relevant directory

  • Wait until this refresh has completed (I do this by pinging the API every few seconds until it gives a result)

  • Request stats on the directory

Rather than logging in for every single request, I'd much rather log in once, then continue using the same token until the token expires (which results in a 401), at which point I'll log in again and get a new token (the API doesn't have a token refresh method).

I've found a library that works with Axios called axios-auth-refresh which:

  • Intercepts requests that return a 401 error

  • Sends a different request to re-authenticate (and get a new token)

  • Sends the original request again with the new token

The axios-auth-refresh library is supposed to pause all other requests using the same Axios instance while the auth refresh logic is running, but I can't seem to get this to work.

My code is here: https://gist.github.com/wipash/ce87e6941d3ea378009c7a819f338b6c

Explanation of how it works:

  • In server.js I call an internal API which returns a list of directory names and associated info.

  • For each directory in this list, call the GetFolderInfo method from nmcapi.js, and eventually resolve all these promises and return all the results

GetFolderInfo does the following:

  • Send a post request to the API to trigger a refresh of the statistics for the directory

  • The response to this request provides a new URL to call which provides the status of the refresh, so call this URL every second until it provides yet another URL to call with the actual results

  • Call the final URL and get the results

This flow works perfectly fine if the initial list of directories has only one entry, but as soon as there's more than one it breaks. The first request gets intercepted by the authRefresh logic, but the second request is let straight through without being paused or intercepted, and so fails with a 401.

I have a feeling this is due to me not understanding promises or instances, or a combination of both.

5 Upvotes

0 comments sorted by