Skip to content

Commit

Permalink
* Work In Progress : added "Injector#cancelInjectionsInto()" and "Inj…
Browse files Browse the repository at this point in the history
…ectionMapping#toModule()" ; added a first Synopsis version ; added license
  • Loading branch information
olivierphi committed Aug 25, 2012
1 parent fc78e46 commit 2cef485
Show file tree
Hide file tree
Showing 5 changed files with 272 additions and 4 deletions.
26 changes: 26 additions & 0 deletions LICENSE
@@ -0,0 +1,26 @@
(The MIT License)

Copyright (c) Olivier Philippon <https://github.com/DrBenton>

Contains snippets of code from Q (https://github.com/kriskowal/q)
and Prototype (https://github.com/sstephenson/prototype) libraries.
See their specific licenses for details.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 change: 0 additions & 1 deletion README

This file was deleted.

134 changes: 134 additions & 0 deletions README.md
@@ -0,0 +1,134 @@
# Medic Injector

One of my greatest pleasure as a web developer has been to work with the great [RobotLegs](http://www.robotlegs.org/)
ActionScript framework and its [SwiftSuspenders](https://github.com/tschneidereit/SwiftSuspenders) light-weight IoC container.
These days I do not use Flash ActionScript anymore, but I was missing RobotLegs and SwiftSuspenders so much that I had
to rebuild this minimalist IoC management library in Javascript , strongly inspired by these 2 tools,
in order to find this pleasure again. I hope you wil enjoy it too ! :-)

It allows to wire you application components in an easy, intuitive and efficient way. It can be used in Node.js and in
the browser. If you use [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) in your client-side
Javascript app, it will be particulary easy to add Medic Injector. It is a very agnostic tool, which can be used in
Express server-side applications, Backbone browser-side applications, etc.

## Synopsis

In a "app/bootstrap.js" file, the injection mappings initialization:

```javascript

// Injector instance creation
var Injector = require('medic-injector');//with AMD you would use "require(['medic-injector'], function() { ... })" instead
var injector = new Injector();

// Simplest injections : just simple values
// Every time an entity declares an injection point whose name matches this injection name, this injection point value will
// be automatically set to this injection mapping value.
injector.addMapping('debug').toValue(true);
injector.addMapping('appConfig').toValue({
mode: 'development',
db: {host: 'localhost', db: 'test'},
mail: {host: 'smtp.gmail.com', user: 'webmaster@test.com', password: ''},
});

// Types injections : an instance of the given JS type will be created on demand when an entity declares an injection point
// whose name matches this injection name
injector.addMapping('logger').toValue(Logger).asSingleton();//when "asSingleton()" is used, the first created instance will always be be injected
injector.addMapping('swig').toValue(Swig).asSingleton();

// Module injections : can be used in Node.Js or in an AMD environment
injector.addMapping('subscribeFormTemplate').toModule('./view/subscribe-form-template.html');
injector.addMapping('inherits').toModule('util' 'inherits');

// Providers injections : the given function is triggered on demand when an entity declares an injection point
// whose name matches this injection name
injector.addMapping('csrf')
.toProvider(function () {
return CsrfGenerator.getNewToken();
});
injector.addMapping('db')
.toProvider(function (appConfig) {//the previously defined "app config" will be automatically injected in this provider
var mongoose = require('mongoose');
var db = mongoose.createConnection(appConfig.db.host, appConfig.db.db);
return db;
})
.asSingleton();//shared singleton instance
injector.addMapping('mailer')
.toProvider(function (appConfig) {
var mailer = new Mailer();
mailer.host = appConfig.mail.host;
mailer.user = appConfig.mail.user;
mailer.password = appConfig.mail.password;
return mailer;
})
.asSingleton();//shared singleton instance
injector.addMapping('subscribeFormHtml')
.toProvider(function (csrf, subscribeFormTemplate, swig) { //these previously defined injections mappings will be automatically injected in this provider
var tmpl = swig.compileFile(subscribeFormTemplate);
tmpl.render({
csrf: csrf
});
});
injector.addMapping('currentUser')
.toProvider(function (db, callback) { //Providers can be asynchronous too (if they have a "callback" arg, they are considered as async Providers)
var UserModel = db.model('User');
MyModel.findOne({id: req.session.userId}, function (err, user) {
err && throw err;
callback(user);
});
});
.asSingleton();//shared singleton instance
```

In a "app/subscribe-form.js" file, injection mappings use:
```javascript

var SubscribeForm = function () {

// This prop value will be automatically set to the shared "mailer" instance
this.mailer = null;
// This prop value will be automatically set to a new rendered "subscribe form", with a new CSRF token
this.subscribeFormHtml = null;
// This prop value will be automatically set to the shared "UserModel" instance
this.currentUser = null;

// This JS type will be "auto-injected"
injector.injectInto(this);

};
SubscribeForm.prototype.postInjections = function() {
// This method will be automatically triggered when all this instance injection points will have been resolved
// It's a sort of "post injections" constructor
};
SubscribeForm.prototype.display = function(req, res) {
res.render(this.subscribeFormHtml);
};

module.exports = SubscribeForm;

```

## Documentation

Coming soon...


## Running Tests

To run the test suite just invoke the following command within the repo:

$ npm test


## License
(The MIT License)

Copyright (c) 2012 Olivier Philippon <https://github.com/DrBenton>

Contains snippets of code from [Q](https://github.com/kriskowal/q) and [Prototype](https://github.com/sstephenson/prototype) libraries. See their specific licenses for details.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
92 changes: 89 additions & 3 deletions medic-injector.js
@@ -1,3 +1,12 @@
/*
* This file is part of the Medic-Injector library.
*
* (c) Olivier Philippon <https://github.com/DrBenton>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

(function(context) {

var myDebug = false;
Expand Down Expand Up @@ -71,6 +80,23 @@
return this;
};

/**
* Maps an injection value to the result of a module.
* Use this only in Node.js or AMD environments (needs the presence of a global "require" function).
* @see https://github.com/amdjs/amdjs-api/wiki/AMD
*
* @param {String} modulePathToRequire
* @param {String} [targetModulePropertyName=null]
* @return {InjectionMapping} The <code>InjectionMapping</code> the method is invoked on
* @throws Error
*/
InjectionMapping.prototype.toModule = function (modulePathToRequire, targetModulePropertyName)
{
this._sealed && this._throwSealedException();
this._toModule = {'path': modulePathToRequire, 'prop': targetModulePropertyName || null};
return this;
};

/**
*
* @return {InjectionMapping} The <code>InjectionMapping</code> the method is invoked on
Expand Down Expand Up @@ -118,6 +144,7 @@
} else if (this._toProvider) {

// This InjectionMapping value is retrieved from a Provider function
// This Provider function may itself ask for other injections, and it can be asynchronous.
// It's gonna be... well... a bit less simple :-)

if (this._asSingleton) {
Expand All @@ -134,6 +161,10 @@

this._resolveProvider(callback, context, forceAsync);

} else if (this._toModule) {

this._resolveModule(callback, context, forceAsync);

}
};

Expand Down Expand Up @@ -293,6 +324,44 @@
}
};

/**
*
* @param {Function} callback
* @param {Object} [context=null]
* @param {Boolean} [forceAsync=false]
* @private
*/
InjectionMapping.prototype._resolveModule = function (callback, context, forceAsync)
{
if (typeof require === "undefined") {
throw new Error('Module resolution can be used only when a global "require" method exists (i.e. in Node.js or when using AMD');
}

if (typeof module !== "undefined" && typeof process !== "undefined") {

// Node.js
// --> instant resolution
var moduleResult = require(this._toModule.path);
if (null !== this._toModule.prop) {
moduleResult = moduleResult[this._toModule.prop];
}
this._triggerFunction(callback, [moduleResult], context, forceAsync);

} else {

// AMD
// --> asynchronous resolution
require([moduleResult], bind(function(moduleResult) {
if (null !== this._toModule.prop) {
moduleResult = moduleResult[this._toModule.prop];
}
this._triggerFunction(callback, [moduleResult], context, forceAsync);
}, this));

}

};

/**
*
* @param {Function} func
Expand Down Expand Up @@ -474,6 +543,24 @@
this.injectInto(newInstance, onInstanceReady, null, proceedToInjectionsInPostInjectionsMethodToo);
};

/**
* Set the value of all public properties of the target JS object whose name is an injection mapping to "null".
* This lets you cancel the effect of #injectInto for clean garbage collection.
*
* @param {Object} jsTypeInstance
*/
Injector.prototype.cancelInjectionsInto = function (jsTypeInstance)
{
// Let's scan this JS object instance for injection points...
for (var propName in jsTypeInstance) {
if (!!this._mappings[propName]) {
// This instance property's name matches a registered injection name
// --> let's cancel this injection point
jsTypeInstance[propName] = null;
}
}
};

/**
*
* @param {Array} injectionsNamesArray an Array of Strings
Expand All @@ -494,8 +581,7 @@
callback.call(context, resolvedInjectionPoints);
};

if (0 === nbInjectionsPointsToResolve)
{
if (0 === nbInjectionsPointsToResolve) {
// No arg for this callback ; immediate trigger!
triggerCallback();
return;
Expand Down Expand Up @@ -553,7 +639,7 @@
// Utils

/**
* "nextTick" function from Q's source code
* "nextTick" function from Q source code
* @see https://raw.github.com/kriskowal/q/master/q.js
*
* Copyright 2009-2012 Kris Kowal under the terms of the MIT
Expand Down
23 changes: 23 additions & 0 deletions test/test.js
Expand Up @@ -338,6 +338,29 @@ describe('InjectionMapping', function(){
});
});// end "#toType()" tests

describe('#toModule()', function(){
it('should immediately return a module result in Node.js', function(){
var injector = new Injector();
var counter = 0;
var injectionMapping = injector.addMapping('test').toModule('util');
injectionMapping.resolveInjection(function (injectionValue) {
assert.strictEqual(require('util'), injectionValue);
assert.strictEqual(0, counter);
});
counter++;
});
it('should immediately return a module sub-property result in Node.js when the "targetModulePropertyName" arg is used.', function(){
var injector = new Injector();
var counter = 0;
var injectionMapping = injector.addMapping('test').toModule('util', 'format');
injectionMapping.resolveInjection(function (injectionValue) {
assert.strictEqual(require('util').format, injectionValue);
assert.strictEqual(0, counter);
});
counter++;
});
});// end "#toModule()" tests

describe('#seal()/#unseal()', function(){
it('should seal', function(){
var injector = new Injector();
Expand Down

0 comments on commit 2cef485

Please sign in to comment.