2016-08-18 51 views
0

我想使用快速扩展“基础”REST调用,但我认为我遇到了限制(或者我缺乏理解)。我希望所有REST端点共享相同的基本REST路由。我不想写这些为每个端点服务(即行星,恒星,等...)快速可变基础路由(REST)

app.get('/api/planet/type',function(req,res) { 
    ... 
}); 

app.get('/api/planet/type/:_id',function(req,res) { 
    ... 
}); 

app.post('/api/planet/type',function(req,res) { 
    ... 
}); 

app.patch('/api/planet/type/:_id',function(req,res){ 
    ... 
}); 

app.delete('/api/planet/type/:_id',function(req,res) { 
    ...  
}); 

我宁愿做的是我实现模块中使用可变

require('base-rest')('/api/planet/type',planet-model); 
require('base-rest')('/api/star/type',star-model); 

然后使用一个变量作为基本端点,但它看起来像express可以在运行时处理动态路由。

app.get(baseURL,function(req,res) { 
    ... 
}); 

app.get(baseURL+'/:_id',function(req,res) { 
    ... 
}); 

这可能吗?如果是这样,我该如何做到这一点?

请注意,我用快递V4

+0

所以我猜这是不可能的?任何人? – gpeters

回答

0

这实际上可以完成(有注意事项)。这在Hage的帖子中有所概述。

//base.js 

var express = require('express'); 
var router = express.Router(); 
.... 
router.get('/:id', function(req, res) { 
    .... 
}); 
//Additional routes here 

module.exports = router 

实现文件

//planets.js 
var base = require('./base'); 
app.use('/api/planets',base); 

这里找到全部细节:https://expressjs.com/en/guide/routing.html

有一个警告这不过。我无法将base.js重复使用于多个实现,因为默认情况下,node.js使用单身人士为require('./base')。这意味着当我真的想要一个新的实例时你会得到同样的实例。为什么?因为我想为每个基本路线注入我的模型。

例如:

var model = null; 
module.exports.map = function(entity) { 
    model = entity; 
} 

router.get('/:id', function(req, res) { 
    model.findOne(...) //using mongoose here 
}); 

同样的模型将被用于由于require('./base')跨越多个模块的所有路由是单进口。

如果有人知道这个额外的问题的解决方案,让我知道!

+1

一个潜在解决方案的链接总是值得欢迎的,但是请[在链接附近添加上下文](http://meta.stackoverflow.com/a/8259/169503),以便您的同行用户可以了解它是什么以及为什么在那。如果目标网站无法访问或永久离线,请始终引用重要链接中最相关的部分。考虑到_barely不仅仅是一个链接到外部网站_是一个可能的原因[为什么和如何删除一些答案?](http://stackoverflow.com/help/deleted-answers)。 –

0

也许你想要做这样的事情:

var planet = express.Router() 
planet.get('/type', function (req, res) { ... }) 
planet.get('/type/:id', function (req, res) { ... }) 
planet.post('/type', function (req, res) { ... }) 
planet.post('/type/:id', function (req, res) { ... }) 
planet.delete('/type/:id', function (req, res) { ... }) 

app.use('/api/planet', planet) 

出口路由器作为本地节点模块。