Search code examples
javascriptnode.jskoa

Call module dynamically using variable


Is it possible to call a module and it's function using variables?

I have a koa route:

import Router from 'koa-router';

import one from '../modules/one.js';
import two from '../modules/two.js';
import three from '../modules/three.js';

router.get('/api/:m/:f', async function get(ctx) {
    let { m, f } = ctx.request.params;

    //how to call module.function using m.f()
});
export default router.middleware();    

GET would be called to /api/one/add which would trigger Module one and it's function add. Is that possible?


Solution

  • If you're looking for something like that:

    <code>const modules = {
      one: require('../modules/one'),
      two: require('../modules/two'),
      three: require('../modules/three')
    }
    
    router.get('/api/:m/:f', async function get(ctx) {
        let { m, f } = ctx.request.params;
    
        //how to call module.function using m.f()
        const module = modules[m];
        const fn = module[f];
        fn();
    });
    export default router.middleware();    
    </code>