📜 ⬆️ ⬇️

Simple Dependency Injection in Node.js

After reading a few articles on DI, I wanted to use it in Node.js; after a brief search, it turned out that there are not so many modules for this, the most interesting of them is di.js from Angular, but it didn’t fit me and I decided to write my own.


Why not di.js?



We write our implementation


The most interesting in writing the module was the problem of dynamic transmission to the constructor of arguments.
The most obvious solution is to use apply , but this does not work, since it interacts with methods, not constructors.


For our purpose, you can use the spread operator :


class Test { constructor(a, b) { } } let args = [1, 2] let test = new Test(...args) 

The rest of the implementation is quite boring and does not contain anything interesting.


We use the module


I decided to abandon the di.js decorators in favor of the config file. Suppose we describe the architecture of the computer, then in the config we need to describe our classes, the paths to them and their arguments:


 { "Computer": { "class": "./Computer.js", //    "args": ["RAM", "HDD", "CPU", "GPU"] //  }, "RAM": { "class": "./RAM.js", "args": [] }, "HDD": { "class": "./HDD.js", "args": [] }, "CPU": { "class": "./CPU.js", "args": ["RAM"] }, "GPU": { "class": "./GPU.js", "args": [] } } 

Computer class, like everyone else, is pretty simple:


 'use strict' class Computer { constructor(ram, hdd, cpu, gpu) { this._cpu = cpu this._gpu = gpu this._hdd = hdd this._ram = ram } } module.exports = Computer 

Now at the entry point of our application we use the module:


 const Injector = require('razr')(__dirname, './path/to/your/config.json') //        const computer = Injector.get('Computer') //     Computer 

It is worth noting that in the config file you need to specify the path to the class relative to the entry point of the application.


That's all. Thanks to everyone who read it. But reference on GitHub - https://github.com/Naltox/razr and NPM - http://npmjs.com/package/razr


')

Source: https://habr.com/ru/post/306276/


All Articles