Skip to content

Instantly share code, notes, and snippets.

@johanneslumpe
Forked from tappleby/0_example.js
Last active November 3, 2015 18:23
Show Gist options
  • Save johanneslumpe/40a57ff683d0bfe8a000 to your computer and use it in GitHub Desktop.
Save johanneslumpe/40a57ff683d0bfe8a000 to your computer and use it in GitHub Desktop.
redux request middleware using superagent and es6 promises.
import { createStore, applyMiddleware, compose } from 'redux';
import request from 'superagent-es6-promise';
import thunkMiddlware from 'redux-thunk';
import promiseMiddleware from 'redux-promise';
import logMiddleware from './middleware/log';
import requestMiddleware from './middleware/request';
// Create request middleware with our execute logic, return promise.
const executeRequestMiddleware = requestMiddleware((req, getState) => {
const { session: { token } } = getState();
if (token) {
req.set('Authorization', 'Bearer ' + token);
}
return req.promise();
});
// Compose middleware
const finalCreateStore = compose(
applyMiddleware(
thunkMiddlware, executeRequestMiddleware, promiseMiddleware, logMiddleware
),
createStore
);
// Create our redux instance
const store = finalCreateStore((state = {}) => state, {
session: {
token: 'foo'
}
});
// Dispatch request.
store.dispatch({
type: 'REQUEST_THING',
request: (execute) =>
execute(request.get('http://httpbin.org/delay/3'))
.then((resp) => resp.body.headers)
});
// Apply custom execute function for executing requests, converts to
// FSA compliant payload.
export default function requestMiddleware(execute) {
return ({dispatch, getState}) => {
function executeWithStateGetter(...args) {
return execute(...args, getState);
}
return next => action => {
if (typeof action.request !== 'function') {
return next(action);
}
const { request: actionRequest, ...rest } = action;
return next({
...rest,
payload: actionRequest(executeWithStateGetter)
});
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment