forked from vagabond-systems/jpmc-task-2
-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Expand file tree
/
Copy pathDataStreamer.ts
More file actions
53 lines (46 loc) · 1.56 KB
/
DataStreamer.ts
File metadata and controls
53 lines (46 loc) · 1.56 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
export interface Order {
price: number; // Change from Number to number for consistency
size: number; // Change from Number to number for consistency
}
/**
* The datafeed server returns an array of ServerRespond with 2 stocks.
* We do not have to manipulate the ServerRespond for the purpose of this task.
*/
export interface ServerRespond {
stock: string;
top_bid: Order;
top_ask: Order;
timestamp: Date;
}
class DataStreamer {
// The URL where datafeed server is listening
static API_URL: string = 'http://localhost:8080/query?id=1';
/**
* Send request to the datafeed server and executes callback function on success
* @param callback callback function that takes JSON object as its argument
*/
static getData(callback: (data: ServerRespond[]) => void): void {
const request = new XMLHttpRequest();
request.open('GET', DataStreamer.API_URL, true); // Use asynchronous request
request.onload = () => {
if (request.status === 200) {
try {
const data = JSON.parse(request.responseText);
callback(data);
} catch (e) {
console.error('Error parsing response data:', e);
alert('Failed to parse server response.');
}
} else {
console.error('Request failed with status:', request.status);
alert('Request failed with status ' + request.status);
}
};
request.onerror = () => {
console.error('Network error occurred');
alert('Network error occurred. Please try again later.');
};
request.send();
}
}
export default DataStreamer;