节点将变量值转换为变量名以用于解构赋值

Node convert variable value to variable name for use in destructuring assignment

我有一个包含 index.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')     
})

Symbols?

好的,决定使用哈希表或字典查找以避免重复一堆 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)