refactor: tidy

This commit is contained in:
cha0s 2020-07-17 01:36:32 -05:00
parent 8868a7d99b
commit d62f5fbfa3

View File

@ -36,12 +36,14 @@ export function createSocketServer(httpServer) {
passport.session()(socket.handshake, undefined, next); passport.session()(socket.handshake, undefined, next);
}); });
socketServer.io.use((socket, next) => { socketServer.io.use((socket, next) => {
// eslint-disable-next-line no-param-reassign /* eslint-disable no-param-reassign */
socket.handshake.channel = parseChannel(socket.handshake.query.referrer); socket.handshake.channel = parseChannel(socket.handshake.query.referrer);
socket.handshake.userId = socket.handshake.user ? socket.handshake.user.id : 0;
/* eslint-enable no-param-reassign */
next(); next();
}); });
socketServer.io.use(async (socket, next) => { socketServer.io.use(async (socket, next) => {
const {user} = socket.handshake; const {userId} = socket.handshake;
const join = promisify(socket.join.bind(socket)); const join = promisify(socket.join.bind(socket));
await Promise.all( await Promise.all(
channelsToHydrate(socket.handshake) channelsToHydrate(socket.handshake)
@ -49,11 +51,10 @@ export function createSocketServer(httpServer) {
.map(async (channel) => { .map(async (channel) => {
await join(channel); await join(channel);
const users = await channelUsers(channel); const users = await channelUsers(channel);
const id = user ? user.id : 0; if (-1 === users.indexOf(userId)) {
if (-1 === users.indexOf(id)) { socketServer.send(new Join({channel, id: userId}), channel);
socketServer.send(new Join({channel, id}), channel);
} }
await set(`${channel}:users:${socket.id}`, user ? user.id : 0); await set(`${channel}:users:${socket.id}`, userId);
}), }),
); );
next(); next();
@ -86,14 +87,13 @@ export function createSocketServer(httpServer) {
}); });
socket.on('disconnect', async () => { socket.on('disconnect', async () => {
const socketKeys = await keys(pubClient, `*:users:${socket.id}`); const socketKeys = await keys(pubClient, `*:users:${socket.id}`);
const {user} = req; const {userId} = req;
if (socketKeys.length > 0) { if (socketKeys.length > 0) {
const channels = socketKeys.map((key) => key.split(':')[0]); const channels = socketKeys.map((key) => key.split(':')[0]);
await Promise.all(channels.map(async (channel) => { await Promise.all(channels.map(async (channel) => {
const userCounts = await channelUserCounts(channel); const userCounts = await channelUserCounts(channel);
const id = user ? user.id : 0; if (1 === userCounts[userId]) {
if (1 === userCounts[id]) { socketServer.send(new Leave({channel, id: userId}), channel);
socketServer.send(new Leave({channel, id}), channel);
} }
})); }));
await del(socketKeys); await del(socketKeys);