Exploring how this community works and helps
Published: 2024-04-07 13:40:28

Hello, 
I am a new member here, and as I have heard dev helps us to learn new things and also helps in resolving issues and errors that is long lasting and persist for days.
So, Starting with the first issue, I am stuck at Redis error. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0oq8tbbi4tvi77ncisma.png)
```
  "dependencies": {
    "@pdf-lib/fontkit": "^1.1.1",
    "@peculiar/x509": "^1.6.1",
    "@socket.io/redis-adapter": "^8.0.0",
    "aspose.cells": "^23.8.0",
    "asposewordscloud": "^23.8.0",
    "aws-sdk": "^2.1227.0",
    "axios": "^0.26.1",
    "bard-ai": "^1.5.4",
    "cheerio": "^1.0.0-rc.12",
    "compression": "^1.7.4",
    "cors": "^2.8.5",
    "crypto-js": "^4.1.1",
    "csv-parser": "^3.0.0",
    "csv-writer": "^1.6.0",
    "dotenv": "^16.0.3",
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "express-fileupload": "^1.2.0",
    "express-session": "^1.17.1",
    "fabric-ca-client": "^2.2.4",
    "fabric-client": "^1.4.16",
    "fabric-network": "^2.2.4",
    "firebase-admin": "^11.3.0",
    "form-data": "^4.0.0",
    "fs": "0.0.1-security",
    "fs-extra": "^8.1.0",
    "fuzzball": "^2.1.2",
    "fuzzyset": "^1.0.7",
    "google-protobuf": "^3.14.0",
    "html-pdf": "^2.2.0",
    "imap": "^0.8.19",
    "jsdom": "^23.0.1",
    "jsonwebtoken": "^8.5.1",
    "jspdf": "^2.5.1",
    "libreoffice-convert": "^1.4.1",
    "libsodium-wrappers": "^0.7.13",
    "lodash": "^4.17.21",
    "log4js": "^4.5.0",
    "mailparser": "^3.5.0",
    "md5": "^2.3.0",
    "md5-file": "^5.0.0",
    "moment": "^2.29.3",
    "mongodb": "^5.1.0",
    "mongoose": "^6.8.4",
    "mysql2": "^2.2.5",
    "natural": "^6.3.0",
    "needle": "^2.6.0",
    "node-blob": "0.0.2",
    "node-cron": "^3.0.2",
    "node-rsa": "^1.1.1",
    "nodemailer": "^6.4.17",
    "nodemon": "^2.0.18",
    "package-lock": "^1.0.5",
    "papaparse": "^5.4.1",
    "path": "^0.12.7",
    "paypal-rest-sdk": "^1.8.1",
    "payu-sdk": "ssh://git@github.com/siddhant-tradereboot/payu-sdk-node.git",
    "pdf-lib": "^1.16.0",
    "pdf-parse": "^1.1.1",
    "pdfkit": "^0.13.0",
    "pdfreader": "^1.2.8",
    "prompt-sync": "^4.2.0",
    "razorpay": "^2.8.3",
    "readline-sync": "^1.4.10",
    "referral-code-generator": "^1.0.8",
    "request": "^2.88.2",
    "rss-parser": "^3.9.0",
    "rss-to-json": "^2.1.0",
    "sequelize": "^5.22.3",
    "sequelize-values": "^1.1.0",
    "socket.io": "^4.5.4",
    "socket.io-redis": "^5.4.0",
    "string-similarity": "^4.0.4",
    "temporary": "^1.1.0",
    "uuid": "^8.3.2",
    "uuid4": "^2.0.3",
    "website-scraper": "^5.3.1",
    "xlsx": "^0.16.9"
  },
```

```
const io = require('socket.io')();
// const socketAuth = require('socketio-auth');
// const adapter = require('socket.io-redis');
const { verifyToken } = require('../webApp/auth.js')
const { redisInstance } = require('./redis');
const { checkLaycanTime } = require('./utils')
const { createClient } = require("redis");
const { createAdapter } = require("@socket.io/redis-adapter");

const pubClient = createClient({ url: "redis://localhost:6379" });
const subClient = pubClient.duplicate();

io.adapter(createAdapter(pubClient, subClient));

// const redisAdapter = adapter({
//   host: process.env.REDIS_HOST || 'localhost',
//   port: process.env.REDIS_PORT || 6379
//   // ,
//   // password: process.env.REDIS_PASS || 'password',
// });

// io.adapter(redisAdapter);


// socket initializATION
function initSocket(server) {

  console.log('InitSocket',server)

  io.attach(server,{
    cors: {
      origin: "*",
      methods: [ "GET", "POST" ]
    
    }
  })
  io.on('connection', async (socket) => {
    //console.log("hre", socket.handshake.query.token)
    const tokenData = await verifyToken(socket.handshake.query.token);
    const user = tokenData.data;
    await redisInstance.redisSetSync(`U${user.userID}`, socket.id);
    // console.log("canConnect", canConnect)
    // if (!canConnect) {
    //   return new Error({ id: socket.id, message: 'ALREADY_LOGGED_IN' })
    // }
    // io.emit("notification", ["Contract Created", "Ship Laycan STarted"])
    socket.on('disconnect', async function (err, data) {
      // console.log('A user disconnected', arguments);
      // console.log("socket", socket)
      await redisInstance.redisRemoveSocketIdSync(`${user.userID}`, socket.id)
    });
    // io.to(socket.id).emit("notification", "data");
    // console.log("in socket", user)
    // socket.use(async (packet, next) => {
    //   console.log(packet);
    //   io.on('disconnect', function (err, data) {
    //     console.log('A user disconnected', arguments);
    //   });
    //   next(new Error('validation error'));
    // });
  });
}

/**
		 * Send notification message passed to list of users.
		 * @param userList list of user's database's primary id userId to sent events to.
		 * @param message notification message to send to the users.
		 * @param callback if provided then return the response in callback(err,success)
		 * @return in case of callback provided, returns callback function else promise object
		 */
exports.sendNotification = function (userList, message, callback) {
  let resp, errors;
  const returnPromise = new Promise(async (resolve, reject) => {
    try {
      //console.log("userList-->", userList)
      let userlistArray = userList.split(',')
      //console.log("userlistArray-->", userlistArray)
      let numOfUsers = userlistArray.length
      for (let i = 0; i < numOfUsers; i++) {
        // console.log("userList[i]", userlistArray[i])
        let userSocketIds = await redisInstance.redisListUserSocketsSync(userlistArray[i]);
        // console.log("userSocketIds-->", userSocketIds)
        userSocketIds.forEach(element => {
          // console.log("emitting message to ->", element)
          io.to(element).emit("notification", message);
        });
      }
      resolve(true)
      resp = true;
    } catch (e) {
      reject(e);
      errors = e;
    }
  })
  if (typeof arguments[3] == "function") {
    //console.log("returning callback")
    callback(resp, errors)
  } else {
    return returnPromise
  }
}

/**
* Send notification message passed to list of users.
* @param to user's database's primary id userId to sent message to.
* @param from user's database's primary id userId from where message sent.
* @return return the control.
*/
exports.sendMessage = async function (to, from) {
  let userSocketIds = await redisInstance.redisListUserSocketsSync(to);
  userSocketIds.forEach(element => {
    io.to(element).emit("chat", to, from);
  });
  return;
}

// testing script for testing sendNotification function

// setInterval(() => {
//   let typeA = ['success', 'error', 'info', 'warn']
//   let randomNo = getRandomInt(4)
//   console.log("randomNo-->", randomNo)
//   exports.sendNotification('47', {
//     notif_type: 1,
//     contract_no: "CONTRACT_NO",
//     event: "NEW_NOTIF",
//     message: "NEW Notification",
//     type: typeA[randomNo]
//   }, (err, data) => {
//     console.log("err,data", err, data)
//   })
// }, 5000)

// function getRandomInt(max) {
//   return Math.floor(Math.random() * Math.floor(max));
// }

exports.initSocket = initSocket

```
PLease friends, help me here!