moduli
As your Node.js project gets larger, you will face some dependency issues:
Where to initiate required modules/components, how to exports those modules in order to use them correctly or dealing with stubs within your tests.
In Java for example, you got frameworks like Spring for handling the issues mentioned above.
Moduli aims to tackle those issues:
This library will manage your dependencies. It will let you concentrate on your app logic instead of requiring modules manually, taking care of instantiation/initialization and working hard to make your code testable.
How it works?
- you configure all the desired modules & injections (very easy...)
- moduli initializes & injects all of your dependencies
- your app is ready to run!
Your project modules will look like this:
function MessageService($db, $utils, $logger, $userService) {
this.db = $db;
//...
}
MessageService.prototype.getAllMessages = function () {
return this.db.messages.find();
};
// ...
module.exports = MessageService;
As you can see it cleans your code - zero lines for require/resolve/initiate dependencies
Usage
First, install via npm:
- npm:
npm install moduli --save
You can find an example in this repo under example/
Besides configurations, this is the only code you will need to run your app:
var moduli = require('moduli');
// initialize moduli with configuration file (or object..)
moduli.initInjector(__dirname, "/modules.json")
.then(function () {
// initialize base dependencies
moduli.init("db", ["dummy-connection-string"]);
//...
// trigger app initialization
moduli.init("app");
});
Configure Modules
Project modules config has the following structure
{
"mode": "string" // "strict" (default) | "tolerant" - if mode is strict, moduli will throw exceptions if you are trying to have a circular reference
"groups": {
"GROUP_NAME": {
"dir": "string", // optional - dir of the desired group from the root of the project (your package.json)
"ignore": ["/IgnoredModule.js"], // optional - modules/directories to ignore within current group
"postfix": "string", // optional - postfix for all child modules
"prefix": "string", // optional - prefix for all child modules
"alias": { // optional - modules renaming
"REAL_MODULE_NAME": "DESIRED_MODULE_NAME"
},
"data": { // REQUIRED - module configurations to apply on all group modules
"type": "class",
"initiate": "multiple"
},
"extends": ["string"] // optional - array of groups to inherit from (only 'data' property)
}
// other groups
},
"modules": {
"MODULE_NAME": {
"module": "string", // REQUIRED - path to the module from the root of the project (your package.json)
"type": "string", // optional - "object" (default) | "function" | "class"
"postConstructor": "string", // optional - an init method to call after require & instantiation
"initiate": "string", // optional - "singleton" (default) | "multiple" - if multiple, each time moduli.get() is called - a new instance will be created. relevant only for 'class'
"injections": { // optional - injections can be defined by adding '
Groups
Group is a way to define multiple modules (which have similar configurations) in a single json property.
By default, all group modules will inherit configurations from the group. In addition, every module can override or add configuration, using inline config (see below).Modules
Is a collection that holds all your project modules. Note that you can use Groups + inline module config instead of defining all your modules manually.npm/node modules
If you want moduli to resolve (inject, initiate...) npm/node modules (no require()), you need to define collection for each one.
The collection can be empty - it means that modules will be loaded with base configuration.
NOTE that if you don't specify npm/node property - npm/node modules won't be resolved by moduli.
Lets say you don't have any special configurations for your npm dependencies, your config json will look like this:
```js
{
"groups": {
// groups...
},
"modules": {
// modules...
}, // An empty object - all npm depenecies can be loaded from within moduli
"npm": {}
}
<h3>moduli.initInjector(projectBasePath, modulesConfig) : promise</h3>
This method should be called before any other call to moduli.<br>
It will reset moduli config, according to the given input:
<ul>
<li><strong>projectBasePath</strong> : string - is the absolute path of the project (if called from project root -> <b>__dirname</b>)</li>
<li><strong>modulesConfig</strong> : object || string - is configurations from moduli (string if you want to load configurations from json file)</li>
</ul>
There are several types of configurations:
* <b>inline</b> <br>
```js
// your module
// ...
module.export["@moduli"] = {
// configurations..
};
- json file
modules.json:
{
"mode": ".."
"modules": {
// ...
}
}
main.js:
var moduli = require('moduli');
// initialize moduli with configuration file (or object..)
moduli.initInjector(__dirname, "/modules.json");
//....
- js object
var config = {
"mode": ".."
"modules": {
// ...
}
}
moduli.initInjector(__dirname, config);
Note that:
- all modules names should be defined in the configuration object.
- specific configurations can be defined inline.
- inline config will override json/object config.
Dependency Injection
Lets look at the following exmaple, AuthService depeneds on: db, utils and UserService instance.
with moduli it can be achived by simply declaring those modules as injections for AuthService:
function AuthService(secret, mydb, utils, userService) {
// ...
}
// ....
module.exports = AuthService;
// NOTE that this can be written in the config json:
module.export["@moduli"] = {
injections: {
"mydb": "db",
"utils": "utils",
"userService": "userService"
}
};
it can be achived also be using '$' before arg name (the arg name without the '$' must match the desired module name):
function AuthService(secret, $db, $utils, $userService) {
// ...
}
// ....
module.exports = AuthService;
API
moduli.get(sName, aArgs) : object
Returns the desired module (will be initiated on demand)
- sName : string - is the name of the desired module (as defined in the modules configurations)
- aArgs : Array - (optional) is array of the arguments for the constructor / init function
example:
```js
// db module - object, reference to the db
var db = moduli.get("db");
db.findOne(query).then(function (result) {
// User module - class (multiple)
var user = moduli.get("User", [result.email, result.password]);
...
});
```moduli.init(sName, aArgs) : void
Initialize the given module. It does hard init, even if the module is an object or singleton class
- sName : string - is the name of the desired module (as defined in the modules configurations)
- aArgs : Array - (optional) is array of the arguments for the constructor / init function
example:
```js
var db = moduli.init("db", ["my-dummy-connection-string");
```moduli.set(sName, oInstance, oModuleData): void
Set module instnace and metadata. Useful for tests, where you want to inject your mock object.
- sName : string - is the name of the desired module (as defined in the modules configurations)
- oInstance : Object - is the desired instance, note that it should be instantiated already
- oModuleData : Object - (optional) is the configuration for the specified module
example:
```js
moduli.set("myModule", {a: "b", c: "d"}, {type: "object"});
```moduli.initInjector(projectBasePath, modulesConfig) : promise
This method should be called before any other call to moduli.
It will reset moduli config, according to the given input:
- projectBasePath : string - is the absolute path of the project (if called from project root -> __dirname)
- modulesConfig : object || string - is configurations from moduli (string if you want to load configurations from json file)
before param name
"ARG_NAME": "MODULE_NAME"
// other injections..
},
"extends": ["string"] // optional - array of groups to inherit from (only module config - 'data' property in group)
}
// other modules...
},
"npm": { // optional - use when you want moduli to resolve npm dependencies
"MODULE_NAME": {
// custom config for npm module
}
},
"node": { // optional - use when you want moduli to resolve node core modules
"MODULE_NAME": {
// custom config for npm module
}
}
}
Groups
Group is a way to define multiple modules (which have similar configurations) in a single json property.By default, all group modules will inherit configurations from the group. In addition, every module can override or add configuration, using inline config (see below).
Modules
Is a collection that holds all your project modules. Note that you can use Groups + inline module config instead of defining all your modules manually.npm/node modules
If you want moduli to resolve (inject, initiate...) npm/node modules (no require()), you need to define collection for each one.The collection can be empty - it means that modules will be loaded with base configuration.
NOTE that if you don't specify npm/node property - npm/node modules won't be resolved by moduli.
Lets say you don't have any special configurations for your npm dependencies, your config json will look like this:
```js { "groups": { // groups... }, "modules": { // modules... },
// An empty object - all npm depenecies can be loaded from within moduli "npm": {} }
__CODE_BLOCK_3__- json file
modules.json:
main.js:
- js object
Note that:
- all modules names should be defined in the configuration object.
- specific configurations can be defined inline.
- inline config will override json/object config.
Dependency Injection
Lets look at the following exmaple, AuthService depeneds on: db, utils and UserService instance.
with moduli it can be achived by simply declaring those modules as injections for AuthService:
it can be achived also be using '$' before arg name (the arg name without the '$' must match the desired module name):
__CODE_BLOCK_8__API
moduli.get(sName, aArgs) : object
Returns the desired module (will be initiated on demand)- sName : string - is the name of the desired module (as defined in the modules configurations)
- aArgs : Array - (optional) is array of the arguments for the constructor / init function
```js // db module - object, reference to the db var db = moduli.get("db"); db.findOne(query).then(function (result) { // User module - class (multiple) var user = moduli.get("User", [result.email, result.password]); ... }); ```
moduli.init(sName, aArgs) : void
Initialize the given module. It does hard init, even if the module is an object or singleton class- sName : string - is the name of the desired module (as defined in the modules configurations)
- aArgs : Array - (optional) is array of the arguments for the constructor / init function
```js var db = moduli.init("db", ["my-dummy-connection-string"); ```
moduli.set(sName, oInstance, oModuleData): void
Set module instnace and metadata. Useful for tests, where you want to inject your mock object.- sName : string - is the name of the desired module (as defined in the modules configurations)
- oInstance : Object - is the desired instance, note that it should be instantiated already
- oModuleData : Object - (optional) is the configuration for the specified module
```js moduli.set("myModule", {a: "b", c: "d"}, {type: "object"}); ```
moduli.initInjector(projectBasePath, modulesConfig) : promise
This method should be called before any other call to moduli.It will reset moduli config, according to the given input:
- projectBasePath : string - is the absolute path of the project (if called from project root -> __dirname)
- modulesConfig : object || string - is configurations from moduli (string if you want to load configurations from json file)