我有一些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 :(得分: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
});
});