Untitled
unknown
plain_text
a year ago
2.9 kB
7
Indexable
const AppError = require('../utils/appError.js');
const User = require('../Models/userModel.js');
const mongoose = require('mongoose');
var clients = new Map();
let ioSocket = null
exports.socketIndex = (io) => {
ioSocket = io
io.use(async (socket, next) => {
const token = socket.handshake.headers.token;
if (!token) {
return next(new AppError('Authentication error',401));
}
const currentUser = await User.findById(toObjectId(token,next));
if (!currentUser) {
return next(new AppError('The user not have access to socket', 401));
}
/* if(currentUser.role != 'retailer' && currentUser.role != 'salesman'){
return next(new AppError('The user not have access to socket', 401));
} */
socket.user = currentUser
next()
});
io.on('connection', socket => {
clients.set(socket.user._id.toString(),socket.id)
socket.on('disconnect', function (data) {
clients.delete(socket.user._id.toString())
console.log('USER DESCONECTED ',socket.id);
console.log('clients ',clients);
});
console.log('USER CONECTED ',socket.id);
socket.on('notification',data =>{
console.log('*** data',data);
console.log('*** clients ',clients)
})
socket.on('msg',data =>{
const Id = clients.get(data.receiveId)
console.log('this id',Id)
console.log('this data ',data)
if(Id){
io.to(Id).emit('notification', { message: 'this client connected', code: 200 });
io.to(Id).emit('msg', { message: data.message})
socket.emit('response', { message: 'this client connected', code: 200 });
}else{
socket.emit('response', { message: 'this client not connected', code: 204 });
socket.emit('notification', { message: 'this client connected', code: 200 });
}
})
socket.on('error', (err) => {
console.error('Socket error:', err);
socket.emit('errorEvent', { message: 'A socket error occurred', code: 400 });
});
});
}
exports.SocketConnectedList = (usersIds) => {
for(let i=0;i<usersIds.length;i++){
const Id = clients.get(usersIds[i].id)
console.log('this id',Id)
console.log('this data ',usersIds[i].data)
if(Id){
ioSocket.to(Id).emit('notification', usersIds[i].data);
}
}
}
const toObjectId = (id, next) => {
try {
return new mongoose.Types.ObjectId(id);
} catch (e) {
return next(new AppError('Invalid id.', 401));
}
};Editor is loading...
Leave a Comment