1

I have a models folder with an index.js file that looks like the following:

'use strict';
const {Dest1} = require('./destinations/dest1');
const {Dest2} = require('./destinations/dest2');
module.exports = {Dest1, Dest2};

I would like to dynamically load these objects based on a condition. I was thinking it might be interesting to have a middleware function that appends a value to the request that I could use to look up the correct object. I could just dynamically load the path, but I'm curious if this is possible.

Middleware:

 function checkDestination(req,res,next){
     if('destination1' in req.body){
          req.path = 'Dest1'
     }
     next()
 }

Router:

router.get('/', checkDestination, (req,res)=>{
    //convert req.path to variable name here
    const {Dest1} = require('./models')     
})

Symbols?

1 Answer 1

1

Ok, decided to go with a hashtable or dictionary look up to avoid repeating a bunch of if statements. If the above is possible, it would be less code but this is pretty clean too.

Middleware:

function checkDestination(req,res,next){
     if('destination1' in req.body){
         req.destination = 'destination1'
     }
     next()
}

HashTable:

const {Dest1} = require('../models')

const destLookUp = {
    destination1:function(destObj){
        return Dest1.create({})
        .then(newDest=>return newDest})
        .catch(error=>{console.log(error)})
    }
}

module.exports = {destLookUp}

Router:

destLookUp[req.destination](destObj)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.