DarkMagic
An experimental dependency injection module that:
- supports "async" modules
- promote testability
- resolve dependencies recursively - detecting circular dependencies
- relies on code conventions
- reduce boilerplate code
- reduce usage of require()
Please read the origin of the name section before proceeding.
example
lib/database.js (async module):
module { // init db connection etc, this module will be "ready" only when the callback is invoked db}
lib/config.js:
module { return }
index.js:
where are all the require calls?
index.js would typically look like this:
var http = var database = var config =
The framework eliminates the need for these declarations by inferring the dependencies from the parameters of a function (it does that using esprima)
how does darkmagic promote testability?
Assuming we want to test a module called loadData that looks like this:
var fs = require('fs')
module.exports = function(filename, callback) {
fs.readFile(filename, callback)
}
If we are writing a test that involves this module we are basically stuck with actually writing a test file to the disk. Of course there are several modules and technics out there to solve this problem. Darkmagic's take on this is described below.
Here is a darkmagic version of this module:
module.exports = function (fs) {
return function loadData(filename, callback) {
fs.readFile(filename, callback)
}
}
looks very similar except that now it is quite easy to inject a mock fs object that will return a result we want in our testing. Lets add a crypto dependency too:
module.exports = function (fs, crypto) {
return function loadData(filename, callback) {
fs.readFile(filename, function (err, data) {
if (err) return callback(err)
// this is not a working example...
var decipher = crypto.createDecipher('aesFoo', 'shhhhhhh')
var result = decipher.update(data)
result += decipher.final()
callbackk(null, result)
})
}
}
Now when testing this code we could do this:
var mockFs = { readFile: ... }
var loadData = require('../lib/loadData')(mockFs, require('crypto'))
... test code here
or we could use darkmagic again, just to replace the fs dependency with a mock:
var mockFs = { readFile: ... }
require('darkmagic').inject(function (loadData) {
.. test code here
}, { fs: mockFs })
How to's
do simple dependency
simple.js:
module { http}
index.js
do callbacks (async modules)
mooFile.js
module { fs}
server.js
module { var server = http server server}
index.js
return a value
config.js
moduleexports = port: 8080
index.js
specify explicit dependencies
this will not work for local files though
index.js
var overrides = 'fooBar': 'MyCrazyNodeModule__name' 'barFoo': '/home/moo/lib/1.js'
listen for new dependencies
index.js
var injector = injector
inject a dash seperated npm module
this will not work for local files though
index.js
add more search paths for local modules
Handling errors
By default errors that occur during the dependency resolution process are simply thrown. Specifying a second callback to the inject method will prevent that and the error handler will be called instead
Dark Magic - Full disclosure
This framework uses a lot of "dark magic" (hence its name) tricks that many will view as dangerous. These people are probably right and you should listen to them!
This module:
-
parses function signature and uses the parameters, literally to load modules, first attempting to require them as they are and then by attaching them to various predefined search paths in your local file system
-
Attempt to inject and invoke recursively EVERY module that exports a function and override the module system cache with the result of the invocation for that module. This behavior is customizable and is turned off by default for external modules (core/node_modules)
-
dashify camelCase (camel-case) parameters when trying to find non local node modules
-
infer that an exported function is async if the last paramter is called "callback"
-
relies heavily on the module system, it does not cache the dependencies you create ** as a result, one injector is use for one process. You can create more injectors but they will share the same underlying require cache.
Fine print
if all else fails you can do
require('darkmagic').inject(main, {
a: {},
b: {},
c: {}
})
function main(a, b, c) {
}
these dependencies will not be cached using the module system but in the injector
TODO:
- provider class factories - parameters that start with an Upper case char will be resolved be looking for a class factory
- static analysis of dependencies
- implement something that will replace flame di with require()s and initializations (code generator)
- document options and customizations
- callbacks that arent getting called ... timeout ? dont let the process exit in anycase