2016-08-18 133 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) 

出口路由器作爲本地節點模塊。