Created
May 15, 2014 16:14
-
-
Save jmreidy/9142291799f0c3aa967a to your computer and use it in GitHub Desktop.
An example of DI with Node and Angular's "DI" system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var context = require('voltron-di'); | |
context | |
.indexModule("Controllers", "server/controllers", { | |
dependencies: ["Core", "Services"], | |
type: "factory" | |
}) | |
.indexModule("DAOs", "server/daos", { | |
dependencies: ["Core"], | |
type: "service" | |
}) | |
.indexModule("Models", "server/models", { | |
dependencies: ["Core"], | |
type: "service" | |
}) | |
.indexModule("Services", "server/services", { | |
dependencies: ["Core", "DAOs"], | |
type: "factory" | |
}) | |
.indexCore({ | |
additionalModules: { | |
"env": require("../config") | |
}, | |
aliases: { | |
"st": "static", | |
"body-parser": "bodyParser", | |
"csurf": "csrf", | |
"cookie-session": "session", | |
"knex": "Knex" | |
} | |
}) | |
.module("App", ["Core", "Controllers"]); | |
context.module("Core") | |
.factory("RouterFactory", function (express) { | |
return function () { return express.Router(); }; | |
}) | |
.factory("knex", function (Knex, env) { | |
return Knex.initialize(env.database); | |
}); | |
context.module("App") | |
.factory("server", require("./index")); | |
module.exports = context; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
voltron-di is on Github, but is not really documented at all or tested right now. It's a thin wrapper of NG's DI system, with some convenience functions thrown in.
indexModule will walk a subtree of files and wire them up to the appropriate ng-di module, camelCasing the names as needed. So server/controllers/admin/userController.js would be made accessible in the Controllers module as adminUserController.
indexCore creates a Core module with Node core's modules, and anything in your dependencies in your package.json. It can also alias module names.
Otherwise, things work the same as ng-di. The nice thing is that none of the required files have to reach out to the context to register themselves or to look anything up - although one could argue that tying constructor argument names to injectable signatures is itself a service lookup.
Note that I never inject lodash/underscore or Bluebird/Q, and just use CJS requires for those. They're never going to be tested since they're pure plumbing, and they'd need to be injected into EVERY file, so there's no point.