feat(ws): send history data and update data with web socket

Added following logic:
1. New clients receive 15 entry history from history file
2. After that, every 10 seconds when new entry is generated it is sent
out to all connected clients
This commit is contained in:
Leons Aleksandrovs
2025-07-07 16:21:54 +03:00
parent 675f12906e
commit ab26e9881f
5 changed files with 40 additions and 16 deletions

View File

@@ -14,7 +14,7 @@ export default class HistoryFile {
*/
writeToFile() {
try {
fs.writeFileSync(this.path, JSON.stringify(this.history));
fs.writeFileSync(this.path, JSON.stringify(this.history, null, 2));
return true;
} catch (err) {
console.error(`Failed to write data to history file: ${err.message}`);

6
backend/consts.js Normal file
View File

@@ -0,0 +1,6 @@
// Define global constants for min and max values
export const MAX = 100;
export const MIN = 0;
// Define range for random number generation
export const RANGE = 0.3; // +-0.3 -> +-30% of previous number

View File

@@ -1 +0,0 @@
[]

View File

@@ -1,26 +1,41 @@
import { WebSocketServer } from 'ws';
import HistoryFile from './classes/HistoryFile.js';
import { MIN, MAX, RANGE } from './consts.js';
import { randomInt, randomInRange } from './utils/random.js';
// Define WebSocket server
const wss = new WebSocketServer({ port: 8080 });
// Define History file class
// For managing data state beyond restart
const history = new HistoryFile('data.json');
// Define WebSocket server
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
// On successful connection, we send history data to the client
// After that, we procceed sending data update every 10 seconds
console.log('Client connected');
ws.on('message', (message) => {
console.log(`Received message => ${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
ws.send('Hello! Message from server.');
ws.send(JSON.stringify({ type: 'history', data: history.history }));
});
console.log('WebSocket server is running on ws://localhost:8080');
// Generate initial random number, or take it from the history if that exists
let previousNumber = randomInt(MIN, MAX);
if (history.history.length > 0) {
previousNumber = history.history[history.history.length - 1].number;
console.log(`Previous number: ${previousNumber}`);
}
/*
* Execute every 10 seconds
* This will update hisotry data, by appending new entry
* Then save this data to a history file
* And notify all clients about new data entry
*/
setInterval(() => {
const newNumber = randomInRange(previousNumber, RANGE, MIN, MAX);
const newEntry = history.append(newNumber);
// Send new entry to all connected clients
wss.clients.forEach((client) => {
if (client.readyState !== WebSocket.OPEN) return;
client.send(JSON.stringify({ type: 'update', data: newEntry }));
});
}, 10 * 1000);

4
backend/nodemon.json Normal file
View File

@@ -0,0 +1,4 @@
{
"watch": ["."],
"ignore": ["node_modules/**", "data.json"]
}