节点/快速 - 重构路由

时间:2016-02-04 16:59:42

标签: node.js express

我有以下节点/快速代码;

// Requires
var app     = require("express")();
var handler = require("./routes/session");

// Routes
app.post("/session", handler.sessionGetNew);
app.get("/session", handler.sessionGetAll);
app.get("/session/:sessionid", handler.sessionGetOne);
app.put("/session/:sessionid", handler.sessionUpdate);
app.delete("/session/:sessionid", handler.sessionDelete);

// Listener
app.listen(9000);

console.log("Listening.....");

有没有办法将路由重构为类似这个伪代码的东西?

app.route("/session"),
  .post(handler.session....)
  .get(handler.session.....)

app.route("/session/:sessionid"),
  .post(handler.session....)
  .get(handler.session....)
  .put(handler.session....)

2 个答案:

答案 0 :(得分:2)

您可以使用Router Middleware

<强> app.js

var app     = require('express')();
var session = require('./routes/session');

app.use('/session', session);

app.listen(9000, function() {
  console.log('listening');
});

<强>路由/ session.js

var router = require('express').Router();
var handler = require('./lib/sessionHandler'); // this was 'handler' in app.js

router.post('/', handler.sessionGetNew);
router.get('/', handler.sessionGetAll);

router.get('/:sessionid', handler.sessionGetOne);
router.put('/:sessionid', handler.sessionUpdate);
router.delete('/:sessionid', handler.sessionDelete);

module.exports = router;

答案 1 :(得分:0)

这可以为您提供您想要的内容

function routReductor(route, methods) {
  var goodMethods = ['get', 'post', 'put', 'delete'];
  for (var key in methods) {
    if (goodMethods.indexOf(key) == -1) continue;
    app[key](route, methods[key])
  }
}

routReductor('/:sessionid', {
  get: handler.sessionGetOne,
  put: handler.sessionUpdate,
  delete: handler.sessionDelete
});