Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed Updated App and Graph Components for Data Streaming and Visualization #286

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 32 additions & 15 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,39 +8,58 @@ import './App.css';
*/
interface IState {
data: ServerRespond[],
showGraph: boolean, // Add showGraph property
}

/**
* The parent element of the react app.
* It renders title, button and Graph react element.
*/
class App extends Component<{}, IState> {
private interval: NodeJS.Timeout | null = null; // Add interval property

constructor(props: {}) {
super(props);

this.state = {
// data saves the server responds.
// We use this state to parse data down to the child element (Graph) as element property
data: [],
showGraph: false, // Initialize showGraph to false
};
}

/**
* Render Graph react component with state.data parse as property data
*/
renderGraph() {
return (<Graph data={this.state.data}/>)
if (this.state.showGraph) {
return <Graph data={this.state.data} />;
}
return null;
}

/**
* Get new data from server and update the state with the new data
*/
getDataFromServer() {
DataStreamer.getData((serverResponds: ServerRespond[]) => {
// Update the state by creating a new array of data that consists of
// Previous data in the state and the new data from server
this.setState({ data: [...this.state.data, ...serverResponds] });
});
if (this.interval) {
clearInterval(this.interval); // Clear existing interval if any
}

this.interval = setInterval(() => {
DataStreamer.getData((serverResponds: ServerRespond[]) => {
// Update the state by creating a new array of data that consists of
// Previous data in the state and the new data from server
this.setState((prevState) => ({
data: [...prevState.data, ...serverResponds]
}));
});
}, 1000); // Fetch data every second
}

componentWillUnmount() {
if (this.interval) {
clearInterval(this.interval); // Clean up interval on unmount
}
}

/**
Expand All @@ -54,20 +73,18 @@ class App extends Component<{}, IState> {
</header>
<div className="App-content">
<button className="btn btn-primary Stream-button"
// when button is click, our react app tries to request
// new data from the server.
// As part of your task, update the getDataFromServer() function
// to keep requesting the data every 100ms until the app is closed
// or the server does not return anymore data.
onClick={() => {this.getDataFromServer()}}>
onClick={() => {
this.setState({ showGraph: true }); // Show the graph
this.getDataFromServer(); // Start streaming data
}}>
Start Streaming Data
</button>
<div className="Graph">
{this.renderGraph()}
</div>
</div>
</div>
)
);
}
}

Expand Down
37 changes: 25 additions & 12 deletions src/DataStreamer.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
export interface Order {
price: Number,
size: Number,
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,
stock: string;
top_bid: Order;
top_ask: Order;
timestamp: Date;
}

class DataStreamer {
// The url where datafeed server is listening
// The URL where datafeed server is listening
static API_URL: string = 'http://localhost:8080/query?id=1';

/**
Expand All @@ -23,18 +24,30 @@ class DataStreamer {
*/
static getData(callback: (data: ServerRespond[]) => void): void {
const request = new XMLHttpRequest();
request.open('GET', DataStreamer.API_URL, false);
request.open('GET', DataStreamer.API_URL, true); // Use asynchronous request

request.onload = () => {
if (request.status === 200) {
callback(JSON.parse(request.responseText));
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 {
alert ('Request failed');
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;
export default DataStreamer;
12 changes: 9 additions & 3 deletions src/Graph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface IProps {
* Perspective library adds load to HTMLElement prototype.
* This interface acts as a wrapper for Typescript compiler.
*/
interface PerspectiveViewerElement {
interface PerspectiveViewerElement extends HTMLElement {
load: (table: Table) => void,
}

Expand All @@ -32,7 +32,7 @@ class Graph extends Component<IProps, {}> {

componentDidMount() {
// Get element to attach the table from the DOM.
const elem: PerspectiveViewerElement = document.getElementsByTagName('perspective-viewer')[0] as unknown as PerspectiveViewerElement;
const elem = document.getElementsByTagName('perspective-viewer')[0] as unknown as PerspectiveViewerElement;

const schema = {
stock: 'string',
Expand All @@ -47,8 +47,14 @@ class Graph extends Component<IProps, {}> {
if (this.table) {
// Load the `table` in the `<perspective-viewer>` DOM reference.

// Add more Perspective configurations here.
elem.load(this.table);
elem.setAttribute("view", "y_line");
elem.setAttribute("column-pivots", '["stock"]');
elem.setAttribute("row-pivots", '["timestamp"]');
elem.setAttribute("columns", '["top_ask_price"]');
elem.setAttribute("aggregates",
'{"stock":"distinct count", "top_ask_price":"avg", "top_bid_price":"avg", "timestamp":"distinct count"}'
);
}
}

Expand Down