Skip to content

Commit

Permalink
done
Browse files Browse the repository at this point in the history
  • Loading branch information
idoMadarr committed Dec 24, 2023
1 parent 3398cbd commit 6f09b8b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 13 deletions.
5 changes: 4 additions & 1 deletion src/services/redis.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createClient } from 'redis';

const client = createClient({
Production: const client = createClient({
username: process.env.REDIS_USER,
password: process.env.REDIS_PASSWORD,
socket: {
Expand All @@ -10,6 +10,9 @@ const client = createClient({
},
});

// Dev:
// const client = createClient();

client.connect();

client.on('error', error => console.log(`Redis Client Error`, error));
Expand Down
39 changes: 27 additions & 12 deletions src/services/socketIO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,22 @@ let io: any;

export default {
socketInit: (server: any) => {
io = new Server(server, { pingInterval: 25000, pingTimeout: 20000 });
io = new Server(server, { pingInterval: 5000, pingTimeout: 5000 });
console.log('Socket Connected');

io.on('connection', (socket: any) => {
socket.on('auth', async (data: ConnectedOnlineType) => {
// Check if the user already in redis
const user = await client.hGet('onlines', data.id);

// if no, add the user to redis cache with "id" (mongodb's id) as a key
if (!user) {
const userData = { ...data, socketId: socket.id };
await client.hSet('onlines', data.id, JSON.stringify(userData));
socket.broadcast.emit('update-onlines', {
type: 'add',
user: userData,
});
}
// Add the user to redis cache with "id" (mongodb's id) as a key
// 'update' method should handle a case when the user close the app without disconnect
const userData = { ...data, socketId: socket.id };
await client.hSet('onlines', data.id, JSON.stringify(userData));
socket.broadcast.emit('update-onlines', {
type: user ? 'update' : 'add',
user: userData,
});
});

socket.on('message', (data: ChatMessageType) => {
Expand All @@ -57,8 +56,24 @@ export default {
});
});

socket.on('disconnect', () => {
console.log('user disconnected');
socket.on('disconnect', async () => {
const userOffline = (await client.hScan(
'onlines',
0,
socket.id
)) as any;
const { cursor, tuples } = userOffline;

for (const user of tuples) {
const userObj = JSON.parse(user.value);
if (userObj.socketId === socket.id) {
client.hDel('onlines', userObj.id);
socket.broadcast.emit('update-onlines', {
type: 'remove',
user: userObj,
});
}
}
});
});
},
Expand Down

0 comments on commit 6f09b8b

Please sign in to comment.