AllenYuan

action template

Apr 27th, 2020
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import querystring from 'querystring';
  2.  
  3. export default function action(type, host, path, params = {}) {
  4.   return dispatch => {
  5.     // configure target url by path and query params
  6.     const url = `${host}/${path}?${typeof params === 'string' ? params.substring(1) : querystring.stringify(params)}`;
  7.     // initiating http request (set loading state)
  8.     const getDataStart = () => ({
  9.       type: `REQUEST/${type}`,
  10.     });
  11.     // got data
  12.     const getDataOk = payload => ({
  13.       type: `OK/${type}`,
  14.       payload,
  15.     });
  16.     // got error
  17.     const getError = error => ({
  18.       type: `ERROR/${type}`,
  19.       error,
  20.     });
  21.     // fetch data and retry on error
  22.     const fetchDataWIthRetry = delay => fetch(url, path === 'api/metadata' ? { credentials: 'include' } : {})
  23.       .then((response) => {
  24.         // add information to the response if it's an error
  25.         // otherwise just jsonify it and pass it on
  26.         if (!response.ok || !response.status) {
  27.           const err = new Error();
  28.           err.fetchError = true;
  29.           dispatch(getError(response.status));
  30.           if (response.status >= 400 && response.status < 500) {
  31.             err.clientError = true;
  32.             err.message = 'fetch failed - client error';
  33.           } else {
  34.             err.message = 'fetch failed - retrying';
  35.           }
  36.           throw err;
  37.         }
  38.         return response.json();
  39.       })
  40.       // load data into state
  41.       .then(json => dispatch(getDataOk(json)))
  42.       .catch((e) => {
  43.         // error => log and try again with an increasing delay
  44.         console.error(e);
  45.         if (e.fetchError && !e.clientError) {
  46.           setTimeout(() => fetchDataWIthRetry(delay + 3000), delay);
  47.         }
  48.         if (!e.fetchError) {
  49.           throw e;
  50.         }
  51.       });
  52.     // initiate request
  53.     dispatch(getDataStart());
  54.     return fetchDataWIthRetry(1000);
  55.   }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment