2016-07-30 36 views
0

我有一些socket.io端點就像這樣:添加socket.io幹某些任務

io.sockets.on('connection', function (socket) { 
    socket.on('chat message', function (req) { 
     socket.handshake.token.verify((err, decoded) => { 
      console.log(decoded); 
     }); 
    }); 

    socket.on('debug', function (req) { 
     socket.handshake.token.verify((err, decoded) => { 
      console.log(decoded); 
     }); 
    }); 

    socket.on('disconnect', function (req) { 
     socket.handshake.token.verify((err, decoded) => { 
      console.log(decoded); 
     }); 
    }); 
}); 

正如你所看到的,每個端點有重複的任務大約是解碼和驗證令牌。有沒有辦法用中間件或之前的過濾器做到這一點,比如:

io.sockets.on('connection', function (socket) { 
    socket.before((req, res) => { 
     socket.handshake.token.verify((err, decoded) => { 
      console.log(decoded); 
     }); 
    }); 

    // Routes are defined here 
}); 

謝謝。

回答

0

你可以這樣創建自己的函數/方法:

io.sockets.on('connection', function (socket) { 

    socket.onVerify = function(msg, fn) { 
     socket.on(msg, function(data) { 
      socket.handshake.token.verify((err, decoded) => { 
       console.log(decoded); 
      }); 
      fn(data); 
     }); 

    } 

    socket.onVerify('chat message', function (req) { 
     // code here 
    }); 

    socket.onVerify('debug', function (req) { 
     // code here 
    }); 

    socket.onVerify('disconnect', function (req) { 
     // code here 
    }); 
}); 
+0

你太了不起了。我應該把我的頭撞到牆上,因爲之前沒有考慮過這個問題。有沒有什麼理由將其命名爲fn?我通常在JS項目中看到fn,而在其他語言中,它主要是cb。 PS。由於需要15分,因此無法升級。 – Aris

+0

@Doge - 'fn'與'cb'只是個人風格。 – jfriend00