-2
\$\begingroup\$

I have a folder called core with two files inside: index.js and module.js. I'm kidding a little with dependency injection and ES6, and I would like to receive feedback with improvements for my code.

index.js

module.exports = [
  {
     mod: require('./module'),
     inj: ['bluebird']
  }
];

Inside module:

module.exports = function (Promise) {};

I want to inject the bluebird lib inside my module.js, so I created this piece of code:

 glob(path.resolve() + '/core/index.js', (error, paths) => {
    if (error) {
      console.log(error);
    }

    for (let file of paths) {
      let index = require(file);

      if (Object.prototype.toString.call(index) !== '[object Array]') {
        return 'Required path is not an array.'
      }

      for (let options of index) {
        options.mod.apply(options.mod, options.inj.map((mod) => {
          try {
            return require(mod);
          } catch (e) {
            return require(path.resolve() + '/core/' + mod);
          }
        }));
      }
    }
  });

The idea here is to get the index.js and call the module.js with the bluebird library as the first parameter.

It works just fine, but the code is a mess, and I don't know how to use ES6 yet.

\$\endgroup\$
1
\$\begingroup\$

The root problem I see here is why is some other code doing dependency injection for you? Node.js already has dependency injection, why go through all the hoops and do it yourself?

module.js could have been as simple as the following, and it would have done the same thing:

var Promise = require('bluebird');

module.exports = function(){
  ...
}

Now you might say "Oh, glob is for dynamically adding modules and deps" - erm... no. Your array is no different from doing the following wherever you're callong glob, just not in array form and if they just required their own dependencies.

require('./module');
require('./another-module');
// and so on...
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.