Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind middleware to events in socket.io

Right now you can bind middleware to io.use(middleware);, but this is triggered only when a socket connection is made. Is there a way to intercept it before passing it to an event handle like in expressjs?

In other word....

In express.js you can do:

app.get('/', middleware1, middleware2, function(req, res){
    res.end(); 
});

Can I do the same in socket.io?

socket.on('someEvent', middleware1, middleware2, function(data){
    console.log(data); // data is now filtered by 2 previous middlewares
});
like image 922
Maria Avatar asked Jan 29 '16 05:01

Maria


1 Answers

As of Socket.io v2.0.4 (found this while inspecting this) you can use a socket middleware like so:

io.on('connection', (socket) => {
  socket.use((packet, next) => {
    // Handler
    next();
  });
});

Which means that you can set your code like so:

io.on('connection', (socket) => {
    socket.use((packet,next) => {

        if (packet[0] === 'someEvent') {
            if (authorizationCondition) {
                return next(new Error('nope'))
            }
        }
        next();
    })
    socket.on('someEvent', function(data){
        console.log(data);
    });
})

You will then be able to catch errors like this with a client-side

io.on('error', err => { ... }) // err will equal "nope"
like image 55
Luke Avatar answered Sep 18 '22 06:09

Luke