Closed mvidalgarcia closed 3 years ago
I've refactored some of the actions
which were using fetch
to axios
in this PR: https://github.com/reanahub/reana-ui/pull/120
Here is one of the functions which were refactored:
fetch
:
export function requestToken() {
return async dispatch => {
let resp, data;
try {
dispatch({ type: USER_REQUEST_TOKEN });
resp = await fetch(USER_REQUEST_TOKEN_URL, {
method: "PUT",
credentials: "include"
});
} catch (err) {
throw new Error(USER_INFO_URL, 0, err);
}
if (resp.status === 401) {
data = await resp.json();
console.log(data.message);
} else if (resp.ok) {
data = await resp.json();
}
dispatch({ type: USER_TOKEN_REQUESTED, ...data });
return resp;
};
}
axios
:
export const requestToken = () => async (dispatch) => {
dispatch({ type: USER_REQUEST_TOKEN });
return await axios.put(USER_REQUEST_TOKEN_URL, null, { withCredentials: true })
.then(resp => dispatch({ type: USER_TOKEN_REQUESTED, ...resp.data }))
.catch(err => {
dispatch(errorActionCreator(err, USER_INFO_URL));
dispatch({ type: USER_TOKEN_ERROR });
});
};
IMO axios
biggest advantage is that it allows to write less verbose code. Also if the response is not 200, it is easy to catch it as an error while with fetch
you have to check if response status not ok
and throw an error by yourself which leads to verbose code.
From Mozzila Fetch API docs: "An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true." Link: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I'd vote to centralize API calls using axios
@audrium: I guess we need to migrate the remaining
actions
toaxios
and plug theerrorActionCreator
to notify the users when some issue appears
Posted on Mattermost.
Migration to axios done here. It's missing the centralization of all api calls in a single file (client.js
) to avoid repetition and keep all URLs there. It can be a class with meaningful methods that then can be called something like Client.getWorkflows()
, Client.loadConfig()
, etc.
We need to decide whether to use Web API's fetch or axios to perform the calls.