Compare commits
9 Commits
4284804536
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f9c2092e2 | ||
| 48b4c7818c | |||
|
|
3c394bddfb | ||
| 3664079c40 | |||
|
|
3ee7139f6e | ||
|
|
4d8cffa78f | ||
|
|
f0c94fa3ee | ||
|
|
ab26e9881f | ||
|
|
675f12906e |
71
README.md
71
README.md
@@ -0,0 +1,71 @@
|
||||
# Vue with WebSockets
|
||||
|
||||
This is a simple project that demonstrates how to use WebSockets with a Vue.js frontend and a Node.js backend.
|
||||
|
||||
## Runnin application
|
||||
|
||||
The application can be run using Docker and Docker Compose.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Docker
|
||||
- Docker Compose
|
||||
|
||||
### Running the application
|
||||
|
||||
To run the application, you can use the following command:
|
||||
|
||||
```bash
|
||||
docker-compose -f development.yml up --build -d
|
||||
```
|
||||
|
||||
This will build and start the frontend, backend, and caddy services in detached mode.
|
||||
|
||||
To stop the application, you can use the following command:
|
||||
|
||||
```bash
|
||||
docker-compose -f development.yml down
|
||||
```
|
||||
|
||||
## Task completions
|
||||
|
||||
### Every task was completed successfully
|
||||
|
||||
- [x] Node.js server that hosts web socket server
|
||||
- [x] Every 10 seconds, generates random number
|
||||
- [x] That is in 0 - 100 range, and doesn't go beyond ±30% range of previous number
|
||||
- [x] Each entry has timestamp
|
||||
- [x] Saves history of numbers in a json file (max 15 entries)
|
||||
- [x] Publishes each new entry to web socket clients
|
||||
- [x] Creates history file if it doesn't exist
|
||||
- [x] Restores history from history file if it exists
|
||||
- [x] Has helper class, that simplifies process of saving and restoring history data
|
||||
- [x] Sends complete history to newly connected clients
|
||||
- [x] Vue.js frontend application, that connects to web socket, and displays data in real time with line chart
|
||||
- [x] Connects to web socket server
|
||||
- [x] Retrieves data, and displays it in line graph
|
||||
- [x] In line graph, x axis is timestamp, and y axis is the received number
|
||||
- [x] Each time when new data is received, it is added to the graph
|
||||
- [x] In graph, there cannot be more that 15 data points
|
||||
- [x] When history data is loaded, it is added to the graph upon web socket connection
|
||||
- [x] Last update timestamp is displayed above the graph
|
||||
- [x] Current connection status (connected/disconnected) is displayed above the graph
|
||||
- [x] Automatic reconnection every 5 seconds, when websocket is disconnected
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
.
|
||||
├── backend # Contains backend server project
|
||||
├── caddy # Contains caddy configuration for docker
|
||||
├── development.yml # Development docker-compose file
|
||||
├── Dockerfile.backend # Docker backend build file
|
||||
├── Dockerfile.frontend # Docker frontend build file
|
||||
├── frontend # Contains frontend project
|
||||
├── README.md
|
||||
└── scripts # Contains scripts for building and running the application (docker)
|
||||
```
|
||||
|
||||
## Honorable mention
|
||||
|
||||
Made with love by **Leons** <3
|
||||
|
||||
@@ -19,5 +19,8 @@ module.exports = {
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
},
|
||||
rules: {},
|
||||
rules: {
|
||||
'import/extensions': 'off',
|
||||
'no-console': 'off',
|
||||
},
|
||||
};
|
||||
1
backend/.gitignore
vendored
Normal file
1
backend/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
data.json
|
||||
24
backend/README.md
Normal file
24
backend/README.md
Normal file
@@ -0,0 +1,24 @@
|
||||
# Backend
|
||||
|
||||
This directory contains the backend server for the application.
|
||||
|
||||
## Purpose
|
||||
|
||||
The backend is a WebSocket server that provides real-time data to the frontend. It also serves as a simple API to get the history of the data.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
.
|
||||
├── classes
|
||||
│ └── HistoryFile.js # HistoryFile class, that provides easy way to save, and read history data
|
||||
├── consts.js # Contains constants for the application
|
||||
├── data.json # History file
|
||||
├── index.js # Entrypoint for backend server
|
||||
├── nodemon.json # Nodemon configuration file (used inside of docker)
|
||||
├── package-lock.json
|
||||
├── package.json
|
||||
├── README.md
|
||||
└── utils
|
||||
└── random.js # Utility that provides random data for backend
|
||||
```
|
||||
82
backend/classes/HistoryFile.js
Normal file
82
backend/classes/HistoryFile.js
Normal 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
6
backend/consts.js
Normal 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
|
||||
@@ -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
4
backend/nodemon.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"watch": ["."],
|
||||
"ignore": ["node_modules/**", "data.json"]
|
||||
}
|
||||
@@ -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
33
backend/utils/random.js
Normal 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));
|
||||
}
|
||||
14
caddy/README.md
Normal file
14
caddy/README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Caddy
|
||||
|
||||
This directory contains the configuration for the Caddy web server.
|
||||
|
||||
## Purpose
|
||||
|
||||
Caddy is used as a reverse proxy to route traffic to the appropriate services:
|
||||
|
||||
- Requests to `/` are served by the frontend Vue.js application.
|
||||
- Requests to `/ws` are proxied to the backend WebSocket server.
|
||||
|
||||
## Project Structure
|
||||
|
||||
- **Caddyfile**: The main configuration file for Caddy. It defines how Caddy should serve the application, including reverse proxying to the frontend and backend services.
|
||||
@@ -1,5 +1,32 @@
|
||||
# Vue 3 + Vite
|
||||
# Frontend
|
||||
|
||||
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
|
||||
This directory contains the frontend Vue.js application.
|
||||
|
||||
## Purpose
|
||||
|
||||
The frontend is a Vue.js application that connects to the backend WebSocket server to receive real-time data and display it in a chart.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
.
|
||||
├── index.html
|
||||
├── package-lock.json
|
||||
├── package.json
|
||||
├── public
|
||||
│ └── vite.svg
|
||||
├── README.md
|
||||
├── src # Contains Vue.js application
|
||||
│ ├── App.vue # Main app component
|
||||
│ ├── assets # Assets directory
|
||||
│ │ └── vue.svg
|
||||
│ ├── components # Components
|
||||
│ │ └── LineChart.vue # Line chart component
|
||||
│ ├── main.js # Vue.js entry point
|
||||
│ ├── style.css # Global css file
|
||||
│ └── utils # Utility functions
|
||||
│ ├── formatDate.js # Timestamp formatting
|
||||
│ └── tryCatch.js # Contains helper function for error handling
|
||||
└── vite.config.js
|
||||
```
|
||||
|
||||
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).
|
||||
|
||||
@@ -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>
|
||||
|
||||
54
frontend/package-lock.json
generated
54
frontend/package-lock.json
generated
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
105
frontend/src/components/LineChart.vue
Normal file
105
frontend/src/components/LineChart.vue
Normal 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>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
5
frontend/src/utils/formatDate.js
Normal file
5
frontend/src/utils/formatDate.js
Normal 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
|
||||
}
|
||||
11
frontend/src/utils/tryCatch.js
Normal file
11
frontend/src/utils/tryCatch.js
Normal 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 };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user