Dependency Injection with ECMAScript 6
Gotcha, yes, he was quite right. So how to acomplish this with ECMScript 6 in a usual manner, as a code snippet or simply a good practice?
First of all create a directory for every module you want to create.
In my case I create the directories assert and logger inside a utils directory.
In the next step we create our content for these directories. That is …
Wow a bunch of stuff for those little modules, but it follows simply a general rule. What does these files mean an do? Just a sec, I will explain.
First of all each directory contains the file with the real code, here assert.js and logger.js.
Second we have a test file for each of it in the same directory, due to the new style to keep everything together in one place.
And last but not least we have an index.js in each. What’s that?
The index.js has the role of an instance that puts everything together.
But let us start from the beginning with the real code that does something.
My first atempt to write an assert module looks like this.
As usual, I import the dependend moduls at first and use them later in the code. But now I want to be able to inject my dependency and that ist done as follows.
I define an internal api as a lamba function that returns the final api with the injected dependendy. Quite easy. Out of the box this api is not really functional, it misses the dependency. So let us create the great combinator, the index.js doing this.
What does it? It simply imports the dependency and creates the final api with it. It is exported in the last step — I love it.
To use it you have to import the index.js from the module that is done in the following way. And you see no index.js at all is used, because it is done automatically for you.
And what about the tests. Here we go.
Also very easy to do, you now can simply mock the dependencies. Therefore you have to import the plain api without the injected dependencies and inject your mock instead. Thats it, not more.
And here are the missing files to get the complete picture.
The logger api
the index.js for the logger
and the spec
By the time you will get hit by the circular dependency problem. In its easiest form it shows up with two files like A and B with A imports B and B imports A. You probably can get rid of it using one of the following ideas:
- Add only those methods into a file that belongs together, has the same purpose. Mixing logging methods and methods to do math does not get together well.
- Try to get rid of it by moving the methods to another file in the same folder and import that directly.
So nothing more to say, I hope I could help a bit and you get the idea.
See you and happy coding.