Untitled
unknown
plain_text
a year ago
2.2 kB
3
Indexable
const AppError = require('../utils/appError.js');
const User = require('../Models/userModel.js');
const mongoose = require('mongoose');
exports.socketIndex = (io) => {
// var clients =[];
var clients = new Map();
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('msg',data =>{
const Id = clients.get(data.receiveId)
console.log('this id',Id)
if(Id){
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.on('error', (err) => {
console.error('Socket error:', err);
socket.emit('errorEvent', { message: 'A socket error occurred', code: 400 });
});
});
}
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