|
@@ -0,0 +1,75 @@
|
|
1
|
+import _ from 'lodash';
|
|
2
|
+import XHRInterceptor from 'react-native/Libraries/Network/XHRInterceptor';
|
|
3
|
+
|
|
4
|
+import { UPDATE_NETWORK_REQUESTS } from './actionTypes';
|
|
5
|
+
|
|
6
|
+/**
|
|
7
|
+ * Global index for keeping track of XHR requests.
|
|
8
|
+ * @type {number}
|
|
9
|
+ */
|
|
10
|
+let reqIndex = 0;
|
|
11
|
+
|
|
12
|
+/**
|
|
13
|
+ * Starts intercepting network requests. Only XHR requests are supported at the
|
|
14
|
+ * moment.
|
|
15
|
+ *
|
|
16
|
+ * Ongoing request information is kept in redux, and it's removed as soon as a
|
|
17
|
+ * given request is complete.
|
|
18
|
+ *
|
|
19
|
+ * @param {Object} store - The redux store.
|
|
20
|
+ * @returns {void}
|
|
21
|
+ */
|
|
22
|
+export function startNetInterception({ dispatch, getState }) {
|
|
23
|
+ XHRInterceptor.setOpenCallback((method, url, xhr) => {
|
|
24
|
+ xhr._reqIndex = reqIndex++;
|
|
25
|
+
|
|
26
|
+ const requests = getState()['features/net-interceptor'].requests || {};
|
|
27
|
+ const newRequests = _.cloneDeep(requests);
|
|
28
|
+ const request = {
|
|
29
|
+ method,
|
|
30
|
+ url
|
|
31
|
+ };
|
|
32
|
+
|
|
33
|
+ newRequests[xhr._reqIndex] = request;
|
|
34
|
+
|
|
35
|
+ dispatch({
|
|
36
|
+ type: UPDATE_NETWORK_REQUESTS,
|
|
37
|
+ requests: newRequests
|
|
38
|
+ });
|
|
39
|
+ });
|
|
40
|
+
|
|
41
|
+ XHRInterceptor.setResponseCallback((...args) => {
|
|
42
|
+ const xhr = args.slice(-1)[0];
|
|
43
|
+
|
|
44
|
+ if (typeof xhr._reqIndex === 'undefined') {
|
|
45
|
+ return;
|
|
46
|
+ }
|
|
47
|
+
|
|
48
|
+ const requests = getState()['features/net-interceptor'].requests || {};
|
|
49
|
+ const newRequests = _.cloneDeep(requests);
|
|
50
|
+
|
|
51
|
+ delete newRequests[xhr._reqIndex];
|
|
52
|
+
|
|
53
|
+ dispatch({
|
|
54
|
+ type: UPDATE_NETWORK_REQUESTS,
|
|
55
|
+ requests: newRequests
|
|
56
|
+ });
|
|
57
|
+ });
|
|
58
|
+
|
|
59
|
+ XHRInterceptor.enableInterception();
|
|
60
|
+}
|
|
61
|
+
|
|
62
|
+/**
|
|
63
|
+ * Stops intercepting network requests.
|
|
64
|
+ *
|
|
65
|
+ * @param {Object} store - The redux store.
|
|
66
|
+ * @returns {void}
|
|
67
|
+ */
|
|
68
|
+export function stopNetInterception({ dispatch }) {
|
|
69
|
+ XHRInterceptor.disableInterception();
|
|
70
|
+
|
|
71
|
+ dispatch({
|
|
72
|
+ type: UPDATE_NETWORK_REQUESTS,
|
|
73
|
+ requests: {}
|
|
74
|
+ });
|
|
75
|
+}
|