-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js.flow
84 lines (77 loc) · 2.21 KB
/
index.js.flow
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// @flow
import XXH from 'xxhashjs';
import produce from 'immer';
import _ from 'lodash';
export const CANCELED_REQUEST_ENABLED = 'CANCELED_REQUEST_ENABLED';
export const REMOVE_CANCELED_CURRENT_REQUEST_FROM_STORE = 'REMOVE_CANCELED_CURRENT_REQUEST_FROM_STORE';
/**
* Generate an IdRequest based on xxhashjs
*/
export const generateId = (futureId: any) => XXH.h32(futureId, '0xABCD').toString(16);
/**
* Dispatch a cancelable dispatch
*/
export const cancelRequestDispatch = (dispatch: Function, idToCancel: any) => dispatch({
type: CANCELED_REQUEST_ENABLED,
idRequestToCancel: generateId(idToCancel),
});
/**
* Cancelable is a specific function to allow a method cancel in
* a component.
*/
export const cancelable = (dispatch: Function, myFunction: Function, id: any) => {
myFunction.cancel = () => {
cancelRequestDispatch(dispatch, id);
};
return myFunction;
};
/**
* Redux middleware to handle canceledRequestInReducer
*/
export const cancelRequestMiddleware = ({ getState }) => (next: Function) => (action: Object) => {
const state = getState();
const canceledRequestsState = _.get(state, '_canceledRequest.requests');
if (canceledRequestsState) {
if (action.idRequest) {
const foundTheRequest = canceledRequestsState.find(
requestRegistered => requestRegistered === action.idRequest,
);
if (foundTheRequest) {
action.canceled = true;
next(action);
next({
type: REMOVE_CANCELED_CURRENT_REQUEST_FROM_STORE,
payload: action.idRequest,
});
return next;
}
}
}
const returnValue = next(action);
return returnValue;
};
/**
* Export a reducer wich can be include
* in a redux store
*/
// eslint-disable-next-line
export const _canceledRequest = (
state: Object = {
requests: [],
},
action: Object,
) => produce(state, (draft) => {
switch (action.type) {
case REMOVE_CANCELED_CURRENT_REQUEST_FROM_STORE: {
const findIndex = draft.requests.findIndex(aRequest => aRequest === action.payload);
draft.requests.splice(findIndex, 1);
break;
}
case CANCELED_REQUEST_ENABLED:
draft.requests.push(action.idRequestToCancel);
break;
default:
break;
}
return draft;
});