Excessive use of require () in node.js, mongoose

I am new to Node.js, but very similar to a modular system and require() . At the same time, proceeding from the background C, I feel embarrassed to see that the same require() 'd module is everywhere. All in all, this leads me to some design options that deviate from how things are done in C. For example:

  • Should I require() mongoose in every file that defines the mongoose model? Or enter a mongoose instance in each file that defines the model.
  • Should I require() my mongoose models in every module they need? Or the model vendor, which is transferred and used to provide these models.

Ect. For someone who uses dependency injection a lot - my gut feeling C tells me the require() module only once and passes it as needed. However, taking a look at some of the open source materials is probably not the Node way. require() makes things very easy ..

Is it painful for you to abuse this mechanism?

+4
source share
2 answers

require() caches modules when you use it. When you see the same file or module that is required everywhere, it loads only once, and instead the saved module.exports saved. This means that you can use require everywhere and not worry about performance and memory issues.

+6
source

The cptroot states require a module wherever you need it, instead of passing it, because the argument is safe and also much simpler. However, you should view any call request as a hard-coded dependency that you cannot easily change. For instance. if you want to mock a module to test these hard-coded dependencies, it will hurt.

Thus, passing the module instance as an argument, instead of just requiring it again and again, reduces the number of hard-coded dependencies, because now you are introducing this dependency. For instance. in your tests, it will be useful for you to easily introduce a layout instead.

If you take this road, you will want to use the dependency injection container, which will help you enter all your dependencies and get rid of all the hard-coded calls. To choose an addiction injection container appropriate for your project, you should read this excellent article . Also check out Fire Up! which I implemented.

0
source

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


All Articles