Socket.io emit from Express controllers

前端 未结 1 483
礼貌的吻别
礼貌的吻别 2020-12-31 23:18

I\'m quite new to Node.js / Express, and I\'m using it as a backend for an AngularJS app. I\'ve looked all over StackOverflow for some help on my problem, but I can\'t seem

相关标签:
1条回答
  • 2020-12-31 23:46

    You can use a pattern based on standard JS closures. The main export in logs.js will not be the controller function itself, but a factory function that will accept all needed dependencies, and create the controller:

    exports.create = function(socket) {
      return function(req, res) {
        // write body of api request to mongodb
        socket.emit();
      }
    }
    

    Then, when you want to use it:

    app.route('/logs').post(logs.create(socket));
    

    Since you set up your routes in a separate package, you have to use the same pattern in routes.js - routes should receive the socket to use as a parameter.

    This pattern works well if you want to handle those things with DI later, or test your controllers with mock "sockets".

    0 讨论(0)
提交回复
热议问题