@luongtt/auth-api-middleware

1.0.0 • Public • Published

Auth API Middleware

This is simple package to handle un-authorized (HTTP 401) exception from API. When exception occurred, authApiMiddleware will push all failed APIs to a queue and try call refresh token handler, then it re-calls all the failed APIs again automatically.

Install:

npm i @luongtt/api-auth-middleware

To inject middleware:

First, initializing the middleware:

import authApiMiddleware from './middleware';

authApiMiddleware.init({
  maxRetry: 2, // Default: 3
  refreshTokenHandler: (onSuccess, onError) => {
    /*
     * You need refresh API token here
     * When success, call 'onSuccess' to retry all failed API
     * When fail, call 'onError' to abort all failed API
     */
    refreshTokenPromise().then(onSuccess).catch(onError);
  },
});

Then, you can inject the middleware to Axios function or fetch API:

const injectedGet = authApiMiddleware.injectMiddleware(axios.get);

const injectedFetch = authApiMiddleware.injectMiddleware(fetch);

...

injectedGet('https://api.example.com/')
  .then((res) => console.log(res))
  .catch((err) => console.log(err));

Readme

Keywords

Package Sidebar

Install

npm i @luongtt/auth-api-middleware

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

4.77 kB

Total Files

3

Last publish

Collaborators

  • luongtt