Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

node.js - How to use socket.io in express routes?

I'm using Express with Socket.io but I can't figure out how to use SocKet.io in Express routes.

I end up doing this in "app.js"

...
...

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());

}

var server = http.createServer(app);
var io = require("socket.io").listen(server);


app.get('/', routes.index);
app.get('/users', user.list);
app.post('/cmp', function(request, response) {
    var client = new pg.Client("pg://user:[email protected]/db_name");
    client.connect(function(err) {

      // Get the product_id and bid
      var product_id = request.body.product_id;
      var bid = request.body.bid.split('b')[1];         

      // If not get the connection
      if(err) {
        return console.error('could not connect to postgres', err);
      }


      client.query('select 1 from product_bid where product_id = $1 and number_bid = $2', [product_id, bid], function(err, result) {
        if(err) {
          return console.error('error running query', err);
        }

        if (result.rowCount == 1) {
          // do not insert          

        } else {
          // insert
          // Insert to the DB
          client.query('insert into product_bid (product_id, number_bid) values ($1, $2)', [product_id, bid], function(err, result) {
            if(err) {
              return console.error('error running query', err);
            }

            io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
            response.json(200, {message: "Message received!"});         
            client.end();           

          });
        }

      });
    });
});


server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});



// ---------------
io.on('connection', function(socket){
    console.log("alguem se ligou!");
    socket.emit('event_from_server', {message: 'conectou-se ao servidor'});
});

How can I define the route to "/cmp" like this and passing the var "io" inside?

app.post('/cmp', routes.cmp);

So that in "/routes/cmp.js" I can do something like this:

exports.cmp = function(req, res){
    var product_id = req.body.product_id;
    var bid = req.body.bid.split('b')[1];       

    io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
    response.json(200, {message: "Message received!"});    
};

Some clues?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about a higher order function?

exports.cmp = function(io) {
  return function(req, res){
    var product_id = req.body.product_id;
    var bid = req.body.bid.split('b')[1];       

    io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
    response.json(200, {message: "Message received!"});    
  }
};

and then

app.post('/cmp', routes.cmp(io));

As another option, I'll sometimes format my routes in the following format:

var routes = require('./routes/routes');

routes(app, io);

And then define routes as

module.exports = function(app, io) {
  app.post('/cmp', function(req, res){
    var product_id = req.body.product_id;
    var bid = req.body.bid.split('b')[1];       

    io.sockets.emit("bidSuccess", {product_id: product_id, bid: bid});
    response.json(200, {message: "Message received!"});    
  })
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...