Added WebSockets with funcionality to send messages from any module

This commit is contained in:
unknown 2021-05-19 17:17:24 +02:00
parent 4510a709d4
commit 38f5d3b66a
7 changed files with 84 additions and 21 deletions

21
Socket.js Normal file
View file

@ -0,0 +1,21 @@
const WebSocket = require('ws');
class Socket {
constructor(server) {
this.webSocketServer = new WebSocket.Server({ server })
this.webSocketServer.on('listening', () => {
console.log('socket listen');
})
this.webSocketServer.on('connection', (webSocketClient) => {
console.log('new connection');
})
}
send(msg) {
this.webSocketServer.clients.forEach(client => client.send(msg));
}
}
module.exports = Socket;

20
Sockets.js Normal file
View file

@ -0,0 +1,20 @@
class Sockets {
constructor() {
this.sockets = [];
}
registerSocket(name, socket) {
this.sockets.push({ name, socket });
}
getAllSockets() {
return this.sockets;
}
getSocket(name) {
const socket = this.sockets.find(socket => socket.name === name);
return socket;
}
}
module.exports = new Sockets();

21
api.js Normal file
View file

@ -0,0 +1,21 @@
const express = require('express');
const errorHandler = require('./middleware/errorHandler');
const api = express();
api.get('/', (req, res) => {
res.send('Server is working');
})
// Body parser
api.use(express.json());
// Link controllers with routes
api.use('/api/apps', require('./routes/apps'));
api.use('/api/config', require('./routes/config'));
api.use('/api/weather', require('./routes/weather'));
// Custom error handler
api.use(errorHandler);
module.exports = api;

5
package-lock.json generated
View file

@ -2793,6 +2793,11 @@
"typedarray-to-buffer": "^3.1.5" "typedarray-to-buffer": "^3.1.5"
} }
}, },
"ws": {
"version": "7.4.5",
"resolved": "https://registry.npmjs.org/ws/-/ws-7.4.5.tgz",
"integrity": "sha512-xzyu3hFvomRfXKH8vOFMU3OguG6oOvhXMo3xsGy3xWExqaM2dxBbVxuD99O7m3ZUFMvvscsZDqxfgMaRr/Nr1g=="
},
"xdg-basedir": { "xdg-basedir": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz",

View file

@ -20,7 +20,8 @@
"express": "^4.17.1", "express": "^4.17.1",
"node-schedule": "^2.0.0", "node-schedule": "^2.0.0",
"sequelize": "^6.6.2", "sequelize": "^6.6.2",
"sqlite3": "^5.0.2" "sqlite3": "^5.0.2",
"ws": "^7.4.5"
}, },
"devDependencies": { "devDependencies": {
"nodemon": "^2.0.7" "nodemon": "^2.0.7"

View file

@ -1,30 +1,23 @@
const express = require('express'); const http = require('http');
const { connectDB } = require('./db'); const { connectDB } = require('./db');
const errorHandler = require('./middleware/errorHandler'); const api = require('./api');
const jobs = require('./utils/jobs'); const jobs = require('./utils/jobs');
const colors = require('colors'); const Socket = require('./Socket');
const Sockets = require('./Sockets');
require('dotenv').config(); require('dotenv').config();
const PORT = process.env.PORT || 5005;
connectDB(); connectDB();
const app = express(); // Create server for Express API and WebSockets
const PORT = process.env.PORT || 5005; const server = http.createServer();
server.on('request', api);
app.get('/', (req, res) => { // Register weatherSocket
res.send('Server is working'); const weatherSocket = new Socket(server);
}) Sockets.registerSocket('weather', weatherSocket);
// Body parser server.listen(PORT, () => {
app.use(express.json());
// Link controllers with routes
app.use('/api/apps', require('./routes/apps'));
app.use('/api/config', require('./routes/config'));
app.use('/api/weather', require('./routes/weather'));
// Custom error handler
app.use(errorHandler);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT} in ${process.env.NODE_ENV} mode`.yellow.bold); console.log(`Server is running on port ${PORT} in ${process.env.NODE_ENV} mode`.yellow.bold);
}) })

View file

@ -1,10 +1,12 @@
const schedule = require('node-schedule'); const schedule = require('node-schedule');
const getExternalWeather = require('./getExternalWeather'); const getExternalWeather = require('./getExternalWeather');
const Sockets = require('../Sockets');
const weatherJob = schedule.scheduleJob('updateWeather', '0 */15 * * * *', async () => { const weatherJob = schedule.scheduleJob('updateWeather', '0 */15 * * * *', async () => {
try { try {
await getExternalWeather(); await getExternalWeather();
console.log('weather updated'); console.log('weather updated');
Sockets.getSocket('weather').socket.send('weather updated');
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }