Node.js的最小功能解析路径(Node.js minimal function for pars

2019-09-28 12:34发布

我有一个Node.js的/快速的应用程序的工作,收到像这样的路线:

app.get('/resource/:res', someFunction);
app.get('/foo/bar/:id', someOtherFunction);

这是伟大的,工作正常。

我也使用Socket.IO,并希望有一些服务器的呼叫使用WebSockets,而不是传统的RESTful调用。 不过,我想让它非常干净,几乎使用相同的语法,preferrably:

app.sio.get('/resource/:res', someFunction);

这将使合成的“休息”界面Socket.IO,其中,从程序员的角度来看,他没有做任何事情不同。 只是标记websockets: true从客户端。

我可以处理所有的细节,如自定义的方式在请求动词通过,并分析它们和谁谁,我没有这个问题。 我寻找的唯一的事情就是有些功能要快确实可以解析路线,并正确地路由他们。 例如,

// I don't know how to read the ':bar',
'foo/:bar'

// Or handle all complex routings, such as
'foo/:bar/and/:so/on'

我可以在实际深入挖掘和尝试将此代码自己,或者尝试通过所有的快递源代码阅读和寻找到他们这样做,但我相信它的存在本身。 只是不知道在哪里可以找到它。

UPDATE

robertklep提供了极大的答案,完全解决了这个对我来说。 我将它改编成一个完整的解决方案,这是我张贴在下面的答案。

Answer 1:

您可以使用Express路由器类做繁重:

var io        = require('socket.io').listen(...);
var express   = require('express');
var sioRouter = new express.Router();

sioRouter.get('/foo/:bar', function(socket, params) {
  socket.emit('response', 'hello from /foo/' + params.bar);
});

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

  socket.on('GET', function(url) {
    // see if sioRouter has a route for this url:
    var route = sioRouter.match('GET', url);
    // if so, call its (first) callback (the route handler):
    if (route && route.callbacks.length) {
      route.callbacks[0](socket, route.params);
    }
  });

});

// client-side
var socket = io.connect();
socket.emit('GET', '/foo/helloworld');

你可以在额外的数据显然通过与请求并传递给你的路线处理程序,以及(例如作为额外的参数)。



Answer 2:

robertklep提供了极大的答案,完全解决了这个对我来说。 我将它改编成一个完整的解决方案,这是在以下情况下,其他人想要做同样的事情:

节点(服务器端):

// Extend Express' Router to a simple name
app.sio = new express.Router();
app.sio.socketio = require('socket.io').listen(server, { log: false });

// Map all sockets requests to HTTP verbs, which parse
// the request and pass it into a simple callback.
app.sio.socketio.sockets.on('connection', function (socket) {
  var verbs = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
  for (var i = 0; i < verbs.length; ++i) {
    var go = function(verb) {
      socket.on(verb, function (url, data) {
        var route = app.sio.match(verb, url);
        if (route && route.callbacks.length) {
          var req = {url: url, params: route.params, data: data, socket:socket}
          route.callbacks[0](req);
        }  
      });
    }(verbs[i]);
  }
});

// Simplify Socket.IO's 'emit' function and liken
// it traditional Express routing.
app.sio.end = function(req, res) {
  req.socket.emit('response', req.url, res);
}

// Here's an example of a simplified request now, which 
// looks nearly just like a traditional Express request.
app.sio.get('/foo/:bar', function(req) {
  app.sio.end(req, 'You said schnazzy was ' + req.data.schnazzy);
});

客户端:

// Instantiate Socket.IO
var socket = io.connect('http://xxxxxx');
socket.callbacks = {};

// Similar to the server side, map functions
// for each 'HTTP verb' request and handle the details.    
var verbs = ['get', 'post', 'put', 'path', 'delete'];
for (var i = 0; i < verbs.length; ++i) {
  var go = function(verb) {
    socket[verb] = function(url, data, cb) {
      socket.emit(String(verb).toUpperCase(), url, data);
      if (cb !== undefined) {
        socket.callbacks[url] = cb; 
      }
    }
  }(verbs[i]);
}

// All server responses funnel to this function,
// which properly routes the data to the correct
// callback function declared in the original request.
socket.on('response', function (url, data) {
  if (socket.callbacks[url] != undefined) {
    socket.callbacks[url](data);
  }
});

// Implementation example, params are:
// 1. 'REST' URL,
// 2. Data passed along,
// 3. Callback function that will trigger
//    every time this particular request URL
//    gets a response.
socket.get('/foo/bar', { schnazzy: true }, function(data){
  console.log(data); // -> 'You said schnazzy was true'
});

感谢您的帮助,robertklep!



文章来源: Node.js minimal function for parsing route