Reputation: 6648
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:
app.post()
then sends the input into an exports, which handles all the database connection.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
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