2023-01-17

How to attach user id and socket id to the sessions in socket.io

  • My Question is how can i attach the user id and the Socket id to access it like pair key = value
  • When a user is login to my website i'm using mongodbStore with sessions to detect the user id, saving data and sending data related to the current user id but lately i want to apply notifications for my website so when a user create a post i will save the post in db and save also the publisher id in the same mongo document i want when a user like the post the i will receive the session id of the liked user i want to send the notification to the post publisher that there's a user liked your post now I'm sending the publisher id with the socket event and compare it in the client side and when id is matching the current user the notification will be displayed but that way I'm sending the notification to all connected users i want to send it just to the publisher how can i do that from a different router here's my code
const cors = require("cors");
const express = require("express");
const session = require("express-session");
const MongoDBStore = require("express-mongodb-session")(session);
require("./mongoose");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const users = require("./routers/users");
const posts = require("./routers/posts");

io.on("connection", async (socket) => {
  console.log("a user connected");
  socket.on("connect_error", (err) => {
    console.log(`connect_error due to ${err.message}`);
  });
});

io.on("disconnect", function() {
  console.log("User Disconnected")
})

//Here's i added the socket io to the request to access it from another router
app.use(function (req, res, next) {
  req.io = io;
  next();
});

const store = new MongoDBStore({
  uri: process.env.DATABASE_URL,
  collection: "mySessions",
});
app.use(
  session({
    store,
    name: "sid",
    saveUninitialized: false,
    resave: false,
    secret: `it is a secret!`,
    cookie: {
      maxAge: 1000 * 60 * 60,
      sameSite: true,
    },
  })
);
app.use(users);
app.use(posts)
app.listen(3000)
  • On the other side in posts router
const express = require("express");
const Posts = require("../db/posts");
const Users = require("../db/users");
const router = express.Router();
//Url like that http://locahost:8000/posts/likes?id=1346
router.post("/posts/likes", async function(req, res) {
  const post = await Posts.findById(req.params.id)
  const publusher = post.publisherID
  const liker = req.session.userId;
  const likerName = await Users.findById(liker).select("username");
  req.io.emit("like", {
    receiver: publusher,
    Message: `${likerName.username} liked your post`,
   sender: liker
  });
});
export default router

on the client side i created an api to send the userId to the client side and i'm handling it like that

const socket = io();
let usr;
$.get("/myId").done(data => usr = data.id)
socket.on("like", function (data) {
  if(data.receiver === usr) {
    console.log(data.Message)
  }
})

I want to emit like event just for the publisher like

req.io.to(req.io.sockets[publusher]).emit("like", {message: "done!"})

Can anyone help me to access the publisher socket id from the sessions i checked also how i can wrap socket to sessions https://socket.io/how-to/use-with-express-session but i can't figure out how it works



No comments:

Post a Comment