我有一个模型文件夹,其中包含一个如下所示的索引.js文件:
'use strict';
const {Dest1} = require('./destinations/dest1');
const {Dest2} = require('./destinations/dest2');
module.exports = {Dest1, Dest2};
我想根据条件动态加载这些对象。我在想有一个中间件函数可能会很有趣,它将一个值附加到我可以用来查找正确对象的请求中。我可以动态加载路径,但我很好奇这是否可能。
中间件:
function checkDestination(req,res,next){
if('destination1' in req.body){
req.path = 'Dest1'
}
next()
}
路由器:
router.get('/', checkDestination, (req,res)=>{
//convert req.path to variable name here
const {Dest1} = require('./models')
})
符号?
好的,决定使用哈希表或字典查找以避免重复一堆 if 语句。如果上述是可能的,那么代码会更少,但这也很干净。
中间件:
function checkDestination(req,res,next){
if('destination1' in req.body){
req.destination = 'destination1'
}
next()
}
哈希表:
const {Dest1} = require('../models')
const destLookUp = {
destination1:function(destObj){
return Dest1.create({})
.then(newDest=>return newDest})
.catch(error=>{console.log(error)})
}
}
module.exports = {destLookUp}
路由器:
destLookUp[req.destination](destObj)