MortenMoulder
MortenMoulder

Reputation: 6648

Using Socket.IO together with Express and NodeJS exports

I am trying to connect my Express and Socket connection together. I think I have this setup neatly, but not when I want to do this:

  1. An user creates a new room. POST to the backend Express server.
  2. The app.post() then sends the input into an exports, which handles all the database connection.
  3. When it's saved in the database, broadcast to everyone via sockets that a new room has been added.

Could this be done solely with sockets? Yes. But I'm not about that life.

RoomRouter.js

exports.createRoom = (req, response) => {
    new Room(req.body).save((err, room) => {
        response.status(200).send(room);
    });
};

app.js

/*
 * Express setup is left out, because we don't need to focus on that.
 * "app" is const app = express();
 */
const RoomRouter = require("./RoomRouter");

app.post("/room/create", RoomRouter.createRoom);

io.on("connection", (socket) => {
    //I want to broadcast the room to everyone
    //io.emit("newRoom", room);
});

The Express part works fine and the POST works. Now, how do I connect Socket.IO to that, so I can broadcast to everyone that a new room has been added?

Upvotes: 0

Views: 157

Answers (1)

Sparw
Sparw

Reputation: 2743

I'm not sure of what you really want, but if you want to use socket io in your route, I think you have to declare your route like this :

RoomRouter.js

exports.createRoom = (io) => {
   return (req, response) => {
      new Room(req.body).save((err, room) => {
         io.emit("newRoom", room);
         response.status(200).send(room);
      });
   };
};

And in your app.js

app.post("/room/create", RoomRouter.createRoom(io));

Hope it helps.

Upvotes: 1

Related Questions