Last active
July 3, 2020 19:52
-
-
Save charly-palencia/42e00c30d7b87b308ed2a4702d192c56 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export default function fetchAPI(options, dispatch) { | |
| const {types, url, payload = {}, headers = {}, method, body} = options; | |
| const defaultHeaders = { | |
| // Accept: "application/vnd.api+json", | |
| // "Content-Type": "application/json", | |
| }; | |
| const authenticationHeader = { | |
| }; | |
| const hasValidActionTypes = | |
| !Array.isArray(types) || | |
| types.length !== 3 || | |
| !types.every(type => typeof type === "string"); | |
| if (hasValidActionTypes) { | |
| throw new Error("Expected an array of three string types."); | |
| } | |
| const [requestType, successType, failureType] = types; | |
| function handleResponse(response) { | |
| if (response.status >= 200 && response.status < 300) { | |
| return response; | |
| } | |
| return response.json().then(payload => { | |
| return new Promise((resolve, reject) => { | |
| reject(payload); | |
| }); | |
| }); | |
| } | |
| dispatch({ | |
| type: requestType, | |
| payload, | |
| }); | |
| function formatPayload(response) { | |
| if (response.status === 204) return ""; | |
| return response.json(); | |
| } | |
| return fetch( | |
| `${process.env.REACT_APP_API_DOMAIN}:${process.env.REACT_APP_API_PORT}` + | |
| url, | |
| { | |
| headers: {...defaultHeaders, ...headers, ...authenticationHeader}, | |
| method, | |
| body, | |
| } | |
| ) | |
| .then(response => handleResponse(response)) | |
| .then(formatPayload) | |
| .then(payload => { | |
| dispatch({ | |
| type: successType, | |
| payload, | |
| }); | |
| return payload; | |
| }) | |
| .catch(error => { | |
| dispatch({ | |
| error: error, //handle this error | |
| type: failureType, | |
| }); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment