UNPKG

@boomerang-io/utils

Version:

A library of reusable utilities and hooks for React webapps on the Boomerang platform.

73 lines (66 loc) 2.48 kB
/* eslint-disable no-console*/ import axios from "axios"; /** * Reducer boilerplate to make api calls * * @param {Obj} actions - object with actions regarding this request * @param {Obj} config - axios config * @example * const appsOverviewReset = () => ({ type: types.APPS_OVERVIEW_RESET }); * const fetchAppsOverviewRequest = () => ({ type: types.FETCH_APPS_OVERVIEW_REQUEST }); * const fetchAppsOverviewSuccess = data => ({ type: types.FETCH_APPS_OVERVIEW_SUCCESS, data }); * const fetchAppsOverviewFailure = error => ({ type: types.FETCH_APPS_OVERVIEW_FAILURE, error }); * * const fetchActionCreators = { * reset: appsOverviewReset, * request: fetchAppsOverviewRequest, * success: fetchAppsOverviewSuccess, * failure: fetchAppsOverviewFailure * }; * * const fetchApi = requestFactory(fetchActionCreators); * const fetchAppsOverview = url => dispatch => dispatch(fetchApi.request({ method: "get", url })); * // fecthAppsOverview is called with param url and dispatch the fetchApi method request with the url * const cancelFetchAppsOverview = () => dispatch => dispatch(fecthApi.cancelRequest()); */ var thunkRequestFactory = function thunkRequestFactory(actions) { var CancelToken = axios.CancelToken; var cancel; var cancelRequest = function cancelRequest() { return function (dispatch) { console.log("Request canceled"); cancel("Request Canceled"); dispatch(actions.reset()); }; }; var request = function request(config) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return function (dispatch) { dispatch(actions.request.apply(actions, args)); return axios(config, { cancelToken: new CancelToken(function executor(c) { cancel = c; }) }).then(function (response) { dispatch(actions.success.apply(actions, [response.data].concat(args))); return Promise.resolve(response); }).catch(function (error) { console.log("AXIOS Error :-S", error); if (axios.isCancel(error)) { console.log(error); return; } else { dispatch(actions.failure.apply(actions, [error].concat(args))); return Promise.reject(error); } }); }; }; return { request: request, cancelRequest: cancelRequest }; }; export default thunkRequestFactory;