Free AI web copilot to create summaries, insights and extended knowledge, download it at here
1601
Abstract
frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="a564"><i>session</i> needs a <i>store </i>— that store can be anything; redis, MySQL, it does not care — <b>it just wants a damn store!</b></p><p id="8744">To give a quick example, <b>this is not DI</b>:</p>
<figure id="cf24">
<div>
<div>
<iframe class="gist-iframe" src="/gist/jeffijoe/e302af26c71da11efbe801374e5446d6.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="b4df">We are importing the db module directly, and we therefore depend on it’s location on disk, <i>and</i> on that particular implementation. Most of the time that’s not a big deal, but it makes testing harder — not impossible, but harder nonetheless. Additionally, the module also assumes that the db module is ready (e.g. that a connection has been established).</p><p id="b01a">If we were to convert the above to a test-friendly DI approach, it would look like this:</p>
<figure id="b929">
<div>
<div>
<iframe class="gist-iframe" src="/gist/jeffijoe/7055c36ffe556c17e620585d24566c5f.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="de47">So what’s different? Instead of exporting an object, we export a
Options
function to make the object. The function states what dependencies it needs in order to do it’s thing.</p><p id="0fe6">If you’re familiar with DI in other languages like Java, C# and PHP, here’s a version using ES6 classes that might be more to your liking:</p>
<figure id="480a">
<div>
<div>
<iframe class="gist-iframe" src="/gist/jeffijoe/d40e891896a04d7292aba8e1c544afe6.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="b36f">I personally prefer the functional approach — no <i>this</i> context to worry about.</p><p id="c5ab">Testing the above becomes super simple — you no longer have to worry about monkey-patching <i>require</i> in order to replace the database module with one that connects to a test database — just invoke the function with the module you want it to use!</p>
<figure id="106f">
<div>
<div>
<iframe class="gist-iframe" src="/gist/jeffijoe/429156496df73a0e313d1b4646b02094.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="d7de">If that was all the code that was needed for our app, I could end the article here and call it a day. Luckily, that’s not the case.</p><p id="3c91"><a href="https://readmedium.com/aedc5fd6eed0"><b>Read part 2 where we start building our app!</b></a></p></article></body>