Попытка использовать события emit с socket.io внутри маршрутов - PullRequest
0 голосов
/ 04 октября 2018

Я пытаюсь генерировать события внутри маршрута, используя socket.io.мой маршрут находится в другом файле, который создает уведомление, и мой app.js находится в моем корне, где установлено соединение с socket.io. Я читал о том, как превратить его в вызов функции ... но я понял, какиспользуйте его.

вот мой app.js

var express = require("express");
var app = express();
var middleware = require("./middleware/index.js");
var bodyParser = require("body-parser");
var passport = require("passport");
var LocalStrategy = require("passport-local");
var mongoose = require("mongoose");
var flash = require("connect-flash");
var Book = require("./models/book");
var User = require("./models/user");
var Review = require("./models/reviews"); // comment
var Reserve = require("./models/reserve.js");
var Notification = require("./models/notification.js");
var User = require("./models/user");
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var notifTest = require('./event/returnRouter')(io);


var methodOverride = require("method-override");


//requiring routes
var reviewRoutes = require("./routes/reviews");
var bookRoutes = require("./routes/books");
var indexRoutes = require("./routes/index");
var reserveRoutes = require("./routes/reserve");

//====================================================
app.set('socketio', io);
mongoose.connect("mongodb://localhost:27017/library", { useNewUrlParser: true });
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
app.locals.moment = require('moment')

//====================================================
// Passport Config
//====================================================
app.use(require("express-session")({
    secret: "HICCUP!!",
    resave: false,
    saveUninitialized: false
}));


app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());



//====================================================
//
//====================================================
app.use(async function(req, res, next){
   res.locals.currentUser = req.user;
   if(req.user) {
    try {
      let user = await User.findById(req.user._id).populate('notifications', null, { isRead: false }).exec();
      res.locals.notifications = user.notifications.reverse();
    } catch(err) {
      console.log(err.message);
    }
   }
   res.locals.error = req.flash("error");
   res.locals.success = req.flash("success");
   next();
});

function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.redirect("/login");
    }
}

app.use("/", indexRoutes);
app.use("/library/:id/reviews",reviewRoutes);
app.use("/library",bookRoutes);
app.use("/library/:id/reserve", reserveRoutes);




io.on('connection', function(socket){
  console.log('a user connected');

  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});



//====================================================
//Library Server Start
//====================================================

server.listen(process.env.PORT, process.env.IP, function() {
    console.log("Library server has started");
    console.log("Listening at PORT: " + process.env.PORT);
})

, а затем вот файл вызова функции .. returnRouter.js

var express = require('express');
var router = express.Router();

/* GET home page. */
var returnRouter = function(io) {


    router.post('/message', function(req, res) {
        io.sockets.on('news', function (data) {
    console.log(data);
    io.sockets.emit('my other event', { my: 'data' });
  });
    });

    return router;
}
module.exports = returnRouter;

в конечном итоге ...я хочу иметь возможность отправлять события в моем маршруте, поэтому, когда я нажимаю кнопку, он обновляет мои уведомления ...

reserve.js

    router.post("/", middleware.isLoggedIn,  async function(req, res) {
    //lookup book using id
    // console.log("this is available " + req.body.available);
    var username = req.user.username;
    var userId = req.user._id;
    var available = req.body.available;
    var daysToAdd = 2;
    var id = '5b70bb0f58e4610cf8181b92';
    var reservedBy = {username: username, userId: userId, available: available};
// ===============================================================================
    try {
        let book = await Book.findById(req.params.id);
        let reserve = await Reserve.create(reservedBy);
        // let user = await User.findById(req.user._id).populate('followers').exec();
        let user = await User.findById(id).exec();

        reserve.returnDate = reserve.borrowDate.setDate(reserve.borrowDate.getDate() + daysToAdd);
        reserve.reserved.id = reservedBy.userId;
        reserve.reserved.username = reservedBy.username;
        reserve.save();

        book.reserves.push(reserve);
        if (book.available < 1) {
            req.flash("error", "There are no more available books");
            res.redirect("/library/" + book._id);
        } else {
            book.available--;
            await book.save();
            res.redirect("/library/" + book._id); 
        }

        let newNotification = {
            username:req.user.username,
            bookId: book.id,
            bookName: book.name
        }


        let notification = await Notification.create(newNotification);
        user.notifications.push(notification);
        user.save();


    } catch(err) {
      req.flash('error', 'Something went wrong!');
      res.redirect('back');
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...