package
Dependency injection for Express applications
npm install express-dinjaGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Use dependency injection pattern for Express 4.x applications. Inspired by express-di.
var express = require('express');
var app = express();
var inject = require('express-dinja')(app);
inject('injected', function (req, res, next) {
next(null, 'injected');
});
inject('dependency', function (injected, req, res, next) {
next(null, 'dependency ' + injected);
});
app.get('/', function (dependency, req, res) {
res.json({
dinja: dependency
});
On localhost:8080 you should see:
{
"dinja": "dependency injected"
}Suppose you have this graph of middleware dependencies:

In express there is no built-in way to start execution of middlewares parallel, so you have two choices:
To reduce boilerplate code (you can see it in statusTodos function below) dependency injection pattern was added to express route function. Here is example how would applications look in plain express and with express-dinja:

This module is heavily based on code from express-di, but has additional features, that I think is necessary for full dependency injection.
express.Route.prototype patchingI used benchmark from express-di to compare bare express application performance with patched version. Benchmark takes application with one middleware, that uses dependency injection and after middleware is done - sends 'Hello world' response.
Middleware is faked database connection, which will response in predefined time (horizontal bar) and requests/sec is the vertical bar:

Returns Function, that can inject dependencies into express application app. It will patch route method to enable injections in route-specific methods like use, get, post and etc.
Injects dependency with name name and dependent express middlewares fn.
fn almost identically inherits express middleware signature: function([dependencies], req, res, next) but with two differences:
next(err, value) function accepts two arguments: err and value of dependency.req, res and next names are pre-defined to corresponding arguments of express middleware.
Resolves dependency and calls callback:
function resolve(name, cb) {
var resolved = this.dependencies[name];
if (!resolved) {
return cb(new Error('Unknown dependency: ' + name));
}
return cb(null, resolved);
}You can override it to add caching.
Stores dependency in inject.dependencies object:
function declare(name, fn) {
this.dependencies[name] = fn;
}If you want to use shared singleton as storage, you can override this (do not forget to override inject.resolve as well).
The MIT License (MIT) © Vsevolod Strukchinsky
Estimated unpacked size across 6 packages.
794.2 kB
Includes dependencies.
5 direct · 2 outdated
^0.0.1
0.0.1
^1.5.2
3.2.6
^3.0.0
6.0.0
^1.1.0
1.1.2
^1.0.0
1.1.0