Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kerimdzhanov
Created January 4, 2018 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerimdzhanov/48cc1880f01981835c9d4d3caea0efd7 to your computer and use it in GitHub Desktop.
Save kerimdzhanov/48cc1880f01981835c9d4d3caea0efd7 to your computer and use it in GitHub Desktop.
Redux Query Middleware – Automatically add request headers using custom network interface interceptor.

Example Usage

You need to have the following in your initialization file (index.js or redux/index.js):

...
import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import {entitiesReducer, queriesReducer} from 'redux-query';
import reduxQueryMiddleware from './middleware/reduxQuery';

...

const store = createStore(
  combineReducers({
    ...reducers,
    entities: entitiesReducer,
    queries: queriesReducer
  }),
  getInitialState(),
  composeEnhancers(
    applyMiddleware(
      queryMiddleware(() => store)
    )
  ));

And the reduxQueryMiddleware.js file from this gist.

import {queryMiddlewareAdvanced} from 'redux-query';
import originalNetworkInterface from 'redux-query/dist/commonjs/network-interfaces/superagent';
/**
* Custom Redux Query Network Interface factory.
* @param {function} getStore – redux store provider
*/
function createNetworkInterface(getStore) {
/**
* Custom Redux Query Network Interface extension.
* Attaches default `Accept` header (`application/json`).
* Attaches `Content-Type` header when a json body is provided.
* Attaches `Authorization` header providing an `access_token`
* from the redux store (`state.auth.token`).
*/
return function (url, method, config) {
const headers = {
'Accept': 'application/json',
...(config.headers || {})
};
if (!headers['Content-Type'] && (
method === 'POST' || method === 'PUT'
) && config.body) {
headers['Content-Type'] = 'application/json';
}
headers['X-Requested-With'] = 'XMLHttpRequest';
config.headers = headers;
return originalNetworkInterface(url, method, config);
}
}
/**
* Redux Query Middleware factory.
* @param {function} getStore – redux store accessor
* @return {Middleware}
*/
export default (getStore) => {
return queryMiddlewareAdvanced(createNetworkInterface(getStore))(
state => state.queries,
state => state.entities
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment