socket.io integration, reload connection list after change

This commit is contained in:
Jan Prochazka
2020-01-04 19:22:57 +01:00
parent 4c52e1eb27
commit 235ef4764b
12 changed files with 501 additions and 26 deletions

View File

@@ -5,9 +5,11 @@ const express = require('express');
const router = express.Router();
const { fork } = require('child_process');
const _ = require('lodash');
const datadir = require('../utility/datadir');
const nedb = require('nedb-promises');
const datadir = require('../utility/datadir');
const socket = require('../utility/socket');
module.exports = {
datastore: null,
async _init() {
@@ -32,15 +34,20 @@ module.exports = {
save_meta: 'post',
async save(connection) {
let res;
if (connection._id) {
return await this.datastore.update(_.pick(connection, '_id'), connection);
res = await this.datastore.update(_.pick(connection, '_id'), connection);
} else {
return await this.datastore.insert(connection);
res = await this.datastore.insert(connection);
}
socket.emit('connection-list-changed');
return res;
},
delete_meta: 'post',
async delete(connection) {
return await this.datastore.remove(_.pick(connection, '_id'));
let res = await this.datastore.remove(_.pick(connection, '_id'));
socket.emit('connection-list-changed');
return res;
},
};

View File

@@ -1,10 +1,18 @@
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const cors = require('cors');
const io = require('socket.io');
const useController = require('./utility/useController');
const connections = require('./controllers/connections');
const socket = require('./utility/socket');
const app = express();
const server = http.createServer(app);
socket.set(io(server));
app.use(cors());
app.use(bodyParser.json());
@@ -14,4 +22,4 @@ app.get('/', (req, res) => {
useController(app, '/connections', connections);
app.listen(3000);
server.listen(3000);

13
api/src/utility/socket.js Normal file
View File

@@ -0,0 +1,13 @@
let socket = null;
module.exports = {
set(value) {
socket = value;
},
get() {
return socket;
},
emit(message, data) {
socket.emit(message, data);
},
};