-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathmixpanel-network.js
86 lines (79 loc) · 2.38 KB
/
mixpanel-network.js
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
85
86
import {MixpanelLogger} from "mixpanel-react-native/javascript/mixpanel-logger";
export class MixpanelHttpError extends Error {
constructor(message, errorCode) {
super(message);
this.code = errorCode;
}
}
export const MixpanelNetwork = (() => {
const sendRequest = async ({
token,
endpoint,
data,
serverURL,
useIPAddressForGeoLocation,
retryCount = 0,
}) => {
retryCount = retryCount || 0;
const url = `${serverURL}${endpoint}?ip=${+useIPAddressForGeoLocation}`;
MixpanelLogger.log(token, `Sending request to: ${url}`);
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: `data=${encodeURIComponent(JSON.stringify(data))}`,
});
const responseBody = await response.json();
if (response.status !== 200) {
throw new MixpanelHttpError(
`HTTP error! status: ${response.status}`,
response.status
);
}
const message =
responseBody === 0
? `${url} api rejected some items`
: `Mixpanel batch sent successfully, endpoint: ${endpoint}, data: ${JSON.stringify(
data
)}`;
MixpanelLogger.log(token, message);
} catch (error) {
if (error.code === 400) {
// This indicates that the data was invalid and we should not retry
throw new MixpanelHttpError(
`HTTP error! status: ${error.code}`,
error.code
);
}
MixpanelLogger.warn(
token,
`API request to ${url} has failed with reason: ${error.message}`
);
const maxRetries = 5;
const backoff = Math.min(2 ** retryCount * 2000, 60000); // Exponential backoff
if (retryCount < maxRetries) {
MixpanelLogger.log(token, `Retrying in ${backoff / 1000} seconds...`);
await new Promise((resolve) => setTimeout(resolve, backoff));
return sendRequest({
token,
endpoint,
data,
serverURL,
useIPAddressForGeoLocation,
retryCount: retryCount + 1,
});
} else {
MixpanelLogger.warn(token, `Max retries reached. Giving up.`);
throw new MixpanelHttpError(
`HTTP error! status: ${error.code}`,
error.code
);
}
}
};
return {
sendRequest,
};
})();