orther
5/18/2016 - 12:22 AM

Mikko's example redux API middleware using whatwg-fetch

Mikko's example redux API middleware using whatwg-fetch

import 'whatwg-fetch';

function isRequest({ promise }) {
 return promise && typeof promise === 'function';
}

function checkStatus(response) {
 if (response.status >= 200 && response.status < 300) {
   return response;
 } else {
   const error = new Error(response.statusText || response.status);
   error.response = response.json();
   throw error;
 }
}

function parseJSON(response) {
 return response.json();
}

function makeRequest({ promise, types, ...rest }, next) {
 const [ REQUEST, SUCCESS, FAILURE ] = types;

 // Dispatch your request action so UI can showing loading indicator
 next({ ...rest, type: REQUEST });

 const api = (url, params = {}) => {
   // fetch by default doesn't include the same-origin header.  Add this by default.
   params.credentials = 'same-origin';
   params.method = params.method || 'get';
   params.headers = params.headers || {};
   params.headers['Content-Type'] = 'application/json';
   params.headers['Access-Control-Allow-Origin'] = '*';

   return fetch(url, params)
     .then(checkStatus)
     .then(parseJSON)
     .then(data => {
       // Dispatch your success action
       next({ ...rest, payload: data, type: SUCCESS });
     })
     .catch(error => {
       // Dispatch your failure action
       next({ ...rest, error, type: FAILURE });
     });
 };
 return promise(api);
}

export function createApiMiddleware() {
  return function() {
    return next => action => isRequest(action) ? makeRequest(action, next) : next(action);
  };
}
export function fetchCuratedList(id) {
 return {
   types: [
     Constants.CURATED_LIST_FETCH_REQUESTED,
     Constants.CURATED_LIST_RECEIVE,
     Constants.CURATED_LIST_FETCH_FAILED
   ],
   promise: api => api('/api/curatedlist/' + id)
 }
}