Merge branch 'feat/websocket-graph-stream' into 'main'

feat: data generation and display using web sockets and line graph

See merge request trials9654228/vue-with-websockets!1
This commit is contained in:
2025-07-07 17:14:30 +00:00
17 changed files with 483 additions and 147 deletions

View File

@@ -19,5 +19,8 @@ module.exports = {
parserOptions: {
ecmaVersion: 'latest',
},
rules: {},
rules: {
'import/extensions': 'off',
'no-console': 'off',
},
};

View File

@@ -0,0 +1,82 @@
import path from 'path';
import fs from 'fs';
export default class HistoryFile {
constructor(fileName) {
this.path = path.join(process.cwd(), fileName);
this.history = [];
this.load();
}
/**
* Writes history to file
* @returns {boolean} true if successful, false otherwise
*/
writeToFile() {
try {
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}`);
return false;
}
}
/**
* Reads history file, and returns it as JSON
* @returns {array}
*/
readFromFile() {
try {
const raw = fs.readFileSync(this.path, 'utf-8');
return JSON.parse(raw);
} catch (err) {
console.warn(`Failed at reading history, using empty history: ${err.message}`);
return [];
}
}
/**
* Loads history file, if it exists
* If not, creates empty file
*/
load() {
if (fs.existsSync(this.path)) {
// Read file, and update this.history
const data = this.readFromFile();
this.history = data;
} else {
// Create empty history file, if doesn't exist
this.writeToFile();
}
}
/**
* Saves most recent 15 entries to history file
*/
save() {
// If there's more than 15 entries, we need to save only most recent 15 ones
if (this.history.length > 15) {
this.history = this.history.slice(this.history.length - 15);
}
// Write to history file
this.writeToFile();
}
/**
* Appends new entry to history file
* Returns most recent entry
* @param {number} number
* @returns {object}
*/
append(number) {
const data = { number, timestamp: Date.now() };
// Push new entry to history
this.history.push(data);
// Save history file, and keep only 15 entries
this.save();
// Return most recent entry
return data;
}
}

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

18
backend/data.json Normal file
View File

@@ -0,0 +1,18 @@
[
{
"number": 93,
"timestamp": 1751907679444
},
{
"number": 84,
"timestamp": 1751907689449
},
{
"number": 60,
"timestamp": 1751907699456
},
{
"number": 88,
"timestamp": 1751907709464
}
]

View File

@@ -1,19 +1,40 @@
const WebSocket = require('ws');
import { WebSocketServer } from 'ws';
import HistoryFile from './classes/HistoryFile.js';
import { MIN, MAX, RANGE } from './consts.js';
import { randomInt, randomInRange } from './utils/random.js';
const wss = new WebSocket.Server({ 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) => {
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.');
// On successful connection, we send history data to the client
// After that, we procceed sending data update every 10 seconds
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;
}
/*
* 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"]
}

View File

@@ -1,6 +1,7 @@
{
"name": "backend",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",

33
backend/utils/random.js Normal file
View File

@@ -0,0 +1,33 @@
/**
* Generates a random integer between min and max (inclusive)
* @param {number} min
* @param {number} max
* @returns {number}
*/
export function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
* Generates a random number based on previous number, and provided range
* Also taking into account global provided min and max values
* @param {number} previousNumber
* @param {number} range (0 - 1)
* @param {number} min
* @param {number} max
* @returns {number}
*/
export function randomInRange(previousNumber, range, min, max) {
// Decides on min max range for the next number
// based on range, and previous number
const integerRange = previousNumber * range; // +- 0.3 -> 30%
// Calculate min, and check if its less that global min (eg. 0)
let newMin = previousNumber - integerRange;
if (newMin < min) newMin = min; // sets to global min, for example 0
// calculate max, and check if number is above the global set max (eg. 100)
let newMax = previousNumber + integerRange;
if (newMax > max) newMax = max; // sets to global max, for example 100
return Math.floor(randomInt(newMin, newMax));
}

View File

@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
<title>WebSocket data</title>
</head>
<body>
<div id="app"></div>

View File

@@ -8,11 +8,14 @@
"name": "frontend",
"version": "0.0.0",
"dependencies": {
"chart.js": "^4.5.0",
"chartjs-adapter-date-fns": "^3.0.0",
"eslint": "^8.57.1",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.32.0",
"vite": "^7.0.0",
"vue": "^3.5.17"
"vue": "^3.5.17",
"vue-chartjs": "^5.3.2"
},
"devDependencies": {
"@babel/eslint-parser": "^7.28.0",
@@ -865,6 +868,12 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@kurkle/color": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",
"integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==",
"license": "MIT"
},
"node_modules/@nicolo-ribaudo/eslint-scope-5-internals": {
"version": "5.1.1-v1",
"resolved": "https://registry.npmjs.org/@nicolo-ribaudo/eslint-scope-5-internals/-/eslint-scope-5-internals-5.1.1-v1.tgz",
@@ -1700,6 +1709,28 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/chart.js": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.0.tgz",
"integrity": "sha512-aYeC/jDgSEx8SHWZvANYMioYMZ2KX02W6f6uVfyteuCGcadDLcYVHdfdygsTQkQ4TKn5lghoojAsPj5pu0SnvQ==",
"license": "MIT",
"dependencies": {
"@kurkle/color": "^0.3.0"
},
"engines": {
"pnpm": ">=8"
}
},
"node_modules/chartjs-adapter-date-fns": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/chartjs-adapter-date-fns/-/chartjs-adapter-date-fns-3.0.0.tgz",
"integrity": "sha512-Rs3iEB3Q5pJ973J93OBTpnP7qoGwvq3nUnoMdtxO+9aoJof7UFcRbWcIDteXuYd1fgAvct/32T9qaLyLuZVwCg==",
"license": "MIT",
"peerDependencies": {
"chart.js": ">=2.8.0",
"date-fns": ">=2.0.0"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -1822,6 +1853,17 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/date-fns": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==",
"license": "MIT",
"peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
}
},
"node_modules/debug": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
@@ -4662,6 +4704,16 @@
}
}
},
"node_modules/vue-chartjs": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/vue-chartjs/-/vue-chartjs-5.3.2.tgz",
"integrity": "sha512-NrkbRRoYshbXbWqJkTN6InoDVwVb90C0R7eAVgMWcB9dPikbruaOoTFjFYHE/+tNPdIe6qdLCDjfjPHQ0fw4jw==",
"license": "MIT",
"peerDependencies": {
"chart.js": "^4.1.1",
"vue": "^3.0.0-0 || ^2.7.0"
}
},
"node_modules/vue-eslint-parser": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.2.0.tgz",

View File

@@ -9,11 +9,14 @@
"preview": "vite preview"
},
"dependencies": {
"chart.js": "^4.5.0",
"chartjs-adapter-date-fns": "^3.0.0",
"eslint": "^8.57.1",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.32.0",
"vite": "^7.0.0",
"vue": "^3.5.17"
"vue": "^3.5.17",
"vue-chartjs": "^5.3.2"
},
"devDependencies": {
"@babel/eslint-parser": "^7.28.0",

View File

@@ -1,30 +1,123 @@
<script setup>
import HelloWorld from './components/HelloWorld.vue';
import { ref, onMounted, onUnmounted } from 'vue';
import LineChart from './components/LineChart.vue';
import tryCatchSync from './utils/tryCatch';
import formatTimestamp from './utils/formatDate';
const data = ref([]); // Handles data
const connected = ref(false); // Stores connection state
let socket = null;
// Function for webhook connection handling
function connectWebSocket() {
// Connect to WebSocket server
socket = new WebSocket('/ws');
// Event on connection
socket.onopen = () => {
connected.value = true;
};
// Event on data received
socket.onmessage = (event) => {
// Try to parse socket message
const { data: message, error: parseErr } = tryCatchSync(() => JSON.parse(event.data));
if (parseErr) {
// Stop execution with unparsable data
return;
}
// Load data initial data, or update it
switch (message.type) {
case 'history':
// Initial message with history data
data.value = message.data;
break;
case 'update':
// Update message, with new entry
data.value.push(message.data);
// Keep only 15 entries
if (data.value.length > 15) {
data.value = data.value.slice(-15);
}
break;
default:
// No default behaviour for now
break;
}
};
// Event on socket close
socket.onclose = () => {
// Mark as disconnected, and retry connection in 5 seconds
connected.value = false;
setTimeout(connectWebSocket, 5000);
};
// On socket error
socket.onerror = () => {
// Close socket on error
socket.close();
};
}
// Start WS connection
onMounted(connectWebSocket);
onUnmounted(() => {
// Close socket when component gets unmounted
if (socket) socket.close();
});
</script>
<template>
<div>
<a href="https://vite.dev" target="_blank">
<img src="/vite.svg" class="logo" alt="Vite logo" />
</a>
<a href="https://vuejs.org/" target="_blank">
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
</a>
</div>
<HelloWorld msg="Vite + Vue" />
<main class="container">
<h1 class="text-primary">Live data from WebSocket</h1>
<div class="connection-container">
<div :class="{ connected: connected }" class="circle" />
<p class="text-secondary">{{ connected ? 'Connected' : 'Disconnected' }}</p>
</div>
<div v-if="data.length > 0" class="update-container">
<p class="text-secondary">
Last update:
<span class="text-primary">{{ formatTimestamp(data[data.length - 1].timestamp) }}</span>
</p>
</div>
<LineChart :data="data" />
</main>
</template>
<style scoped>
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
h1 {
text-align: center;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
.update-container {
text-align: center;
}
.logo.vue:hover {
filter: drop-shadow(0 0 2em #42b883aa);
.connection-container {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
.circle {
width: 15px;
height: 15px;
background-color: red;
border-radius: 100%;
}
.connected {
background-color: green;
}
p {
margin: 0;
}
}
</style>

View File

@@ -1,40 +0,0 @@
<script setup>
import { ref } from 'vue';
defineProps({
msg: String,
});
const count = ref(0);
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank">create-vue</a>, the
official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support" target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>

View File

@@ -0,0 +1,105 @@
<script setup>
/**
* LineChart.vue
*
* A reusable line chart component using Chart.js via vue-chartjs.
* Accepts a list of data points as props with the structure:
* [{ number: 42, timestamp: 1720346500000 }]
*/
import { Line } from 'vue-chartjs';
import {
Chart as ChartJS,
LineElement,
PointElement,
LinearScale,
TimeScale,
Title,
Tooltip,
Legend,
} from 'chart.js';
import 'chartjs-adapter-date-fns'; // Enables timestamp formatting with date-fns
import { computed } from 'vue';
// Register required chart.js components
ChartJS.register(LineElement, PointElement, LinearScale, TimeScale, Title, Tooltip, Legend);
// Define props - expects `data` with { number, timestamp }
const props = defineProps({
data: {
type: Array,
required: true,
validator: (value) =>
value.every((p) => typeof p.number === 'number' && typeof p.timestamp === 'number'),
},
});
// Create reactive chart data computed from data prop
const chartData = computed(() => ({
datasets: [
{
label: 'Real time generated number',
data: props.data.map((p) => ({
x: p.timestamp,
y: p.number,
})),
borderColor: '#42b983',
backgroundColor: 'rgba(66, 185, 131, 0.15)',
pointRadius: 3,
tension: 0.4, // smooth curve
fill: true,
},
],
}));
// Define chart configuration options
const chartOptions = {
animation: false,
responsive: true,
maintainAspectRatio: false, // allow flexible height
scales: {
x: {
type: 'time',
time: {
tooltipFormat: 'HH:mm:ss',
displayFormats: {
second: 'HH:mm:ss',
minute: 'HH:mm',
},
},
title: {
display: true,
text: 'Time',
},
},
y: {
beginAtZero: true,
min: 0,
max: 100,
title: {
display: true,
text: 'Number value',
},
},
},
plugins: {
legend: {
display: true,
position: 'bottom',
},
tooltip: {
callbacks: {
// Format tooltip values
label: (context) => `Value: ${context.parsed.y}`,
},
},
},
};
</script>
<template>
<!-- Chart container with max height -->
<div style="height: 600px">
<Line :data="chartData" :options="chartOptions" />
</div>
</template>

View File

@@ -1,79 +1,18 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
background-color: #212437;
font-family: Arial, Helvetica, sans-serif;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
.text-primary {
color: oklch(92.8% 0.006 264.531);
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
.text-secondary {
color: oklch(70.7% 0.022 261.325);
}
.card {
padding: 2em;
}
#app {
max-width: 1280px;
.container {
width: 100%;
max-width: 1140px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,5 @@
// Format timestamp into readable time
export default function formatTimestamp(timestamp) {
const date = new Date(timestamp);
return date.toLocaleString(); // or use toLocaleTimeString() for just the time
}

View File

@@ -0,0 +1,11 @@
/**
* A simple try/catch wrapper for synchronous code
*/
export default function tryCatchSync(callback) {
try {
const data = callback();
return { data, error: null };
} catch (error) {
return { data: null, error };
}
}