Skip to content

Instantly share code, notes, and snippets.

@tomfa
Created August 3, 2016 17:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfa/858c22507de93bccdc9b1949424126f2 to your computer and use it in GitHub Desktop.
Save tomfa/858c22507de93bccdc9b1949424126f2 to your computer and use it in GitHub Desktop.
Redux API middleware: Presuming one is already logged in
import { CALL_API } from 'api';
import * as type from './types';
const USERS_URL = '/users';
export const getUsers = () => {
return {
[CALL_API]: {
url: USERS_URL,
authenticated: true,
types: [type.USERS_REQUEST, type.USERS_SUCCESS, type.USERS_FAILURE]
}
}
}
import axios from 'axios';
import { logout } from 'actions';
const BASE_URL = '/api';
const AUTH_COOKIE_NAME = 'jwt';
const API = axios.create({ baseURL: BASE_URL });
// Action key that carries API call info interpreted by this Redux middleware.
export const CALL_API = Symbol('Call API');
// A Redux middleware that interprets actions with CALL_API info specified.
// Performs the call and promises when such actions are dispatched.
export default store => next => action => { // eslint-disable-line
const callAPI = action[CALL_API];
if (typeof callAPI === 'undefined') {
return next(action);
}
API.interceptors.response.use(response => (
Promise.resolve(response)
), error => {
if (error.status === 401) store.dispatch(logout());
return Promise.reject(error);
});
let { method, url, types, authenticated, data, headers } = callAPI;
method = method || 'GET';
authenticated = authenticated || false;
const [requestType, successType, errorType] = types;
const token = localStorage.getItem(AUTH_COOKIE) || null;
const config = {
method,
url,
data
};
if (authenticated) {
if (token) config.headers = { Authorization: `Bearer ${token}` };
}
if (headers) {
config.headers = headers;
}
next({ type: requestType });
return API.request(config)
.then(res => {
next({
res: res.data,
authenticated,
type: successType
})
})
.catch(err => {
next({
err,
type: errorType
})
console.log(err)
});
};
export const USERS_REQUEST = 'USERS_REQUEST';
export const USERS_SUCCESS = 'USERS_SUCCESS';
export const USERS_FAILURE = 'USERS_FAILED';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment