npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

redux-api-middleware-interceptor

v1.0.4

Published

A Redux API middleware for intercepting API calls.

Downloads

77

Readme

Intercepting APIs with redux-api-middleware made easy

Building single page applications and utilising some kind of API ? Probably you'd want to include some kind of JWT or you'd want to preppend base URL to all of your http requests ? Well redux-api-middleware-interceptor does that kind of stuff for you automatically.

1.1 Installation

npm: npm install redux-api-middleware-interceptor --save

OR

yarn: yarn add redux-api-middleware-interceptor

Note: You must have redux-api-middleware ^2.0.0 installed as peer dependency.

1.2 Usage

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import interceptor from 'redux-api-middleware-interceptor';
import { CALL_API, apiMiddleware } from 'redux-api-middleware';

const apiMiddlewareInterceptor = interceptor(configObj);

const store = createStore(
  reducer,
  applyMiddleware(apiMiddlewareInterceptor, apiMiddleware, thunk) <-- the interceptor must be before apiMiddleware
);

1.3 API

redux-api-middleware-interceptor exports a function that when called with config object returns you a middleware that acts as an interceptor:

interceptor(configObj) <-- returns a redux middleware

1.3.1 configObj.headers (object|function)

Usefull when you want to add additional headers to all of your routes.

Note: If you pass headers that were already provided, then its gonna override original headers.

You can either pass an Object:

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import interceptor from 'redux-api-middleware-interceptor';

const store = createStore(
  reducer,
  applyMiddleware(interceptor({ headers: {'content-type': 'application/json'}), thunk)
);

or if you want more customised solution like adding JWT then you can pass a function instead of object. The first parameter of it will be the already present headers and second will be redux state like so:

Note: It should return an object otherwise it'll default to original headers

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import interceptor from 'redux-api-middleware-interceptor';

const store = createStore(
  reducer,
  applyMiddleware(
    interceptor({
      headers: (origHeaders, state) => {
        // auth being a reducer
        const headers = Object.assign({}, origHeaders);
        if (state.auth.jwt) {
          headers['Authorization'] = `Bearer ${state.auth.jwt}`;
        }
        return headers;
      }
    ),
    thunk
  )
);

There are some Useful functions which you can use when you want to do something like when request fails (e.g showing a toastr automatically or logging out User automatically if statusCode is 401 :D), when request is success or when request is initiated (e.g showing a Youtube like loader and hiding when request resolves)

1.3.2 configObj.getURL(passedUrl: string, state: object): string

Usefull when you don't want to include base URL to all of your http requests. e.g on production API url can be different than development environment.

Note:

  • If getURL is not defined, then interceptor is not gonna do anything.
  • Its gonna throw an error if getURL is not a function.
  • It'll only call this function, when passedUrl is not complete (e.g /foo/1)
  • It should return a string
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import interceptor from 'redux-api-middleware-interceptor';

const store = createStore(
  reducer,
  applyMiddleware(interceptor({
    getURL: (passedURL, state) => `http://abc.com${passedUrl}`
  }), thunk)
);

1.3.3 onRequestInit(state: object)

Usefull when you don't want to show a Youtube like loader when a request is initiated.

Note:

  • If onRequestInit provided is not a function, it'll throw an Error.
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import interceptor from 'redux-api-middleware-interceptor';

const store = createStore(
  reducer,
  applyMiddleware(interceptor({
    onRequestInit: (state) => {
      // show a loader Loader.show()
   	  console.log('Do something');
    }
  }), thunk)
);

1.3.4 onRequestSuccess(state: object, response: object)

Usefull when you want to do something when request has a success response. E.g hiding the Youtube like loader.

Note:

  • If onRequestSuccess provided is not a function, it'll throw an Error.
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import interceptor from 'redux-api-middleware-interceptor';

const store = createStore(
  reducer,
  applyMiddleware(interceptor({
    onRequestSuccess: (state, response) => {
      // show a loader Loader.hide()
   	  console.log('Do something');
    }
  }), thunk)
);

1.3.5 onRequestError(state: object, response: object)

Usefull when you want to do something when request has an error response. E.g Logging out of the app if endpoint returns a 401 code.

Note:

  • If onRequestSuccess provided is not a function, it'll throw an Error.
  • If the response is not JSON, the library will return the ressult as raw_res with is_json=false.
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import interceptor from 'redux-api-middleware-interceptor';

const store = createStore(
  reducer,
  applyMiddleware(interceptor({
    onRequestError: (state, response) => {
      // logout the user if 401 response
      if (response.status_code === 401) {
        // logout user
      }
    }
  }), thunk)
);

I Like it

Please share and don't forget to ⭐️ this repo :)

License

MIT © Hamza Baig