Socket io Notification
Intially the socket will be enabled. To disable socket.io change the "SOCKET_STATUS" form "ON" to "OFF" in the environment file ::: Here is an example of notification with socket io.
Folder Structure API
src/
├── redux/
│ └── SocketUtils.js
Implementation API
const socket = require('socket.io');
const { createAdapter } = require('@socket.io/redis-adapter');
const logger = require('../config/logger');
const { redisClient } = require('./redisCache');
const subClient = redisClient.duplicate();
let io;
const connectSocket = (server) => {
io = socket(server, {
cors: {
origin: '*',
},
});
// redis adaptor
io.adapter(createAdapter(redisClient, subClient));
io.of('/').adapter.on('error', function (error) {
logger.info('Error socket io redis', error);
});
io.on('connection', async (socketConnection) => {
logger.info('Socket connection established');
// joined a room
socketConnection.on('room', (room) => {
socketConnection.join(room);
});
});
return true;
};
const emitSocketUpdate = (params) => {
io.to(params.room).emit(params.socketEvent, params.message, params.unreadCount);
return true;
};
module.exports = {
connectSocket,
emitSocketUpdate,
};
Folder Structure Frontend
src/
├── utilityFunctions/
│ └── SocketUtility.js
Implementation Frontend
import { useState, useContext } from 'react';
import io from 'socket.io-client';
import { toast } from 'react-toastify';
import { useDispatch } from 'react-redux';
import { setCookies } from '../hooks/useCookies';
import envValues from '../enviornment';
export const joinSocketRoom = (room) => {
const socket = io(envValues.REACT_APP_API_FRONT_END, { transports: ['websocket'] });
socket.emit('room', room);
socket.on('newNotificationUpdate', (message, unreadCount) => {
setCookies('UNREADNOTIFICATIONCOUNT', unreadCount);
toast.success(message);
});
socket.on('notificationClearUpdate', (message, unreadCount) => {
setCookies('UNREADNOTIFICATIONCOUNT', unreadCount);
});
};
How to use
Here is an example to emit data from API and receive on the frontend. To emit data from the source(API / Frontend)
const sockerParams = {
room: result.user_id, // user_id is the users id where you want to send the data
socketEvent: 'newNotificationUpdate', // newNotificationUpdate - is the name of the socket event
message: 'You have a new notification.', // Message you want to pass
unreadCount: notificationCount, // notificationCount - is the unread notification count
};
emitSocketUpdate(sockerParams);
This will trigger this function in the socketUtils.js file
const emitSocketUpdate = (params) => {
io.to(params.room).emit(params.socketEvent, params.message, params.unreadCount);
return true;
};
To receive the data in the receiver (API / Frontend)
socket.on('newNotificationUpdate', (message, unreadCount) => { // newNotificationUpdate - is the name of the socket event
setCookies('UNREADNOTIFICATIONCOUNT', unreadCount); // set the unread notification count in the cookie
toast.success(message);
});