Skip to content

Instantly share code, notes, and snippets.

@rybarix
Created October 24, 2016 21:38
Show Gist options
  • Save rybarix/987cc88084b437bce944337c859d6de8 to your computer and use it in GitHub Desktop.
Save rybarix/987cc88084b437bce944337c859d6de8 to your computer and use it in GitHub Desktop.
Reducer for tracing all request from ajax requests
// --------------
// ACTIONS
// --------------
const API_CALL_RESPONSE_STATUS = 'API_CALL_RESPONSE_STATUS';
const API_CALL_RESPONSE_STATUS_200 = 'API_CALL_RESPONSE_STATUS_200';
const API_CALL_RESPONSE_STATUS_401 = 'API_CALL_RESPONSE_STATUS_401';
const API_CALL_RESPONSE_STATUS_422 = 'API_CALL_RESPONSE_STATUS_422';
const GENERAL_API_CALL = 'GENERAL_API_CALL';
/**
* This function should be called from all ajax calls
*/
export const apiCallResponseStatus = (dispatch, code) => {
if (code === 200) {
dispatch(apiCallResponseStatus200());
} else if (code === 401) {
dispatch(apiCallResponseStatus401());
dispatch(push('/logout'));
} else if (code === 422) {
dispatch(apiCallResponseStatus422());
}
};
export const apiCallResponseStatus200 = () => ({
type: API_CALL_RESPONSE_STATUS_200
});
export const apiCallResponseStatus401 = () => ({
type: API_CALL_RESPONSE_STATUS_401
});
export const apiCallResponseStatus422 = () => ({
type: API_CALL_RESPONSE_STATUS_422
});
export const generalApiCall = (time) => ({
type: GENERAL_API_CALL,
time
});
/**
* @param response from server
* return state
*/
export const apiReturn = (response, callback) => {
return dispatch => {
dispatch(apiCallResponseStatus(response.status));
};
};
const currentDate = () => {
const ret = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
return ret;
};
const currentdate = new Date();
export const timestamp =
/**
* Api reducer
*/
const initialState = {
response: 0,
message: '',
// ...
};
export const apiReducer = (state = initialState, action) => {
switch (action.type) {
case API_CALL_RESPONSE_STATUS:
return state;
case API_CALL_RESPONSE_STATUS_200:
return {
...state,
response : 200,
message: ''
};
case GENERAL_API_CALL:
return {
...state,
lastApiCall: currentDate()
};
case API_CALL_RESPONSE_STATUS_422:
return {
...state,
response: 422,
message: '... 422'
};
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment