generated from lucien/api-template
fix: improved websocket usage
This commit is contained in:
parent
fbf7821320
commit
132b1f3c06
7 changed files with 135 additions and 79 deletions
|
@ -1,5 +1,6 @@
|
|||
const jwt = require('jsonwebtoken');
|
||||
const { getConnection, getUser } = require('./mysql');
|
||||
const express = require('express');
|
||||
|
||||
async function checkAuth(req, res, next) {
|
||||
const { token } = req.body;
|
||||
|
@ -23,6 +24,30 @@ async function checkAuth(req, res, next) {
|
|||
}
|
||||
}
|
||||
|
||||
const router = express.Router();
|
||||
const sockets = new Set();
|
||||
|
||||
router.ws('/', function(ws, req) {
|
||||
sockets.add(ws);
|
||||
|
||||
ws.on('close', () => {
|
||||
sockets.delete(ws);
|
||||
});
|
||||
});
|
||||
|
||||
function socketsMiddleware(req, res, next) {
|
||||
req.sockets = {
|
||||
emit: function(data) {
|
||||
for (const socket of sockets) {
|
||||
socket.send(JSON.stringify(data));
|
||||
}
|
||||
}
|
||||
};
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
checkAuth,
|
||||
router,
|
||||
socketsMiddleware,
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue