-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathspeedTestUtils.js
More file actions
57 lines (49 loc) · 1.62 KB
/
speedTestUtils.js
File metadata and controls
57 lines (49 loc) · 1.62 KB
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
const BACK_END_URL = import.meta.env.VITE_BACK_END_URL || 'http://localhost:3000';
export const calculateDownloadSpeed = async () => {
try {
const startTime = Date.now();
const response = await fetch(`${BACK_END_URL}/download`);
if (!response.ok) throw new Error('Network response was not ok');
const blob = await response.blob();
const endTime = Date.now();
const duration = (endTime - startTime) / 1000;
const sizeInBits = blob.size * 8;
return (sizeInBits / duration) / 1e6;
} catch (error) {
console.error('Download speed test failed:', error);
return null;
}
};
export const calculateUploadSpeed = async () => {
try {
const data = new Uint8Array(30 * 1024 * 1024);
const startTime = Date.now();
const response = await fetch(`${BACK_END_URL}/upload`, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/octet-stream',
},
});
if (!response.ok) throw new Error('Network response was not ok');
const endTime = Date.now();
const duration = (endTime - startTime) / 1000;
const sizeInBits = data.length * 8;
return (sizeInBits / duration) / 1e6;
} catch (error) {
console.error('Upload speed test failed:', error);
return null;
}
};
export const calculateLatency = async () => {
try {
const startTime = Date.now();
const response = await fetch(`${BACK_END_URL}/download`);
if (!response.ok) throw new Error('Network response was not ok');
const endTime = Date.now();
return endTime - startTime;
} catch (error) {
console.error('Latency test failed:', error);
return null;
}
};