├── .babelrc ├── .npmignore ├── .gitignore ├── .travis.yml ├── bower.json ├── LICENSE ├── package.json ├── di.js ├── README.md └── di-es6.spec.js /.babelrc: -------------------------------------------------------------------------------- 1 | {"stage": 1} 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/* 3 | common.js 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '0.12' 4 | - '0.11' 5 | - '0.10' 6 | after_success: 7 | - npm run coveralls 8 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "di-decorators", 3 | "version": "0.2.1", 4 | "homepage": "https://github.com/lgvo/di-decorators", 5 | "authors": [ 6 | "Luis Gustavo Vilela de Oliveira " 7 | ], 8 | "description": "Simple Dependency Injection with ES Decorators", 9 | "main": "di.js", 10 | "moduleType": [ 11 | "es6" 12 | ], 13 | "keywords": [ 14 | "es7", 15 | "di", 16 | "depency", 17 | "injection", 18 | "decorators" 19 | ], 20 | "license": "MIT", 21 | "ignore": [ 22 | "**/.*", 23 | "node_modules", 24 | "bower_components", 25 | "test", 26 | "tests" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Luis Gustavo Vilela de Oliveira 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "di-decorators", 3 | "version": "0.2.2", 4 | "description": "Simple Dependency Injection with ES Decorators", 5 | "main": "common.js", 6 | "repository": "lgvo/di-decorators", 7 | "dependencies": {}, 8 | "devDependencies": { 9 | "babel": "~5.6.14", 10 | "chai": "~3.0.0", 11 | "chai-as-promised": "~5.1.0", 12 | "coveralls": "^2.11.4", 13 | "jscoverage": "^0.6.0", 14 | "karma": "~0.12.37", 15 | "mocha": "~2.2.5", 16 | "mocha-lcov-reporter": "0.0.2", 17 | "sinon": "~1.15.4" 18 | }, 19 | "scripts": { 20 | "build": "babel --modules common di.js > common.js", 21 | "clean-coverage": "mkdir -p coverage && rm -Rf coverage/*", 22 | "build-coverage": "npm run clean-coverage && node_modules/.bin/babel di.js >> coverage/di.js && node_modules/.bin/babel di-es6.spec.js >> coverage/di-es6.spec.js && node_modules/.bin/jscoverage coverage/di.js coverage/di.js", 23 | "coverage": "npm run build-coverage && node_modules/.bin/mocha -R html-cov coverage/di-es6.spec.js >> coverage/index.html", 24 | "coveralls": "npm run build-coverage && node_modules/.bin/mocha -R mocha-lcov-reporter coverage/di-es6.spec.js | node_modules/.bin/coveralls", 25 | "test": "mocha --compilers js:babel/register di-es6.spec.js" 26 | }, 27 | "keywords": [ 28 | "di", 29 | "dependency injection", 30 | "decorator", 31 | "decorators", 32 | "es7", 33 | "es next" 34 | ], 35 | "author": "Luis Oliveira (http://github.com/lgvo)", 36 | "license": "MIT" 37 | } 38 | -------------------------------------------------------------------------------- /di.js: -------------------------------------------------------------------------------- 1 | function nsPrefix(str) { 2 | return '__$$' + str; 3 | } 4 | 5 | var symProvider = nsPrefix('provider'), 6 | symInterceptors = nsPrefix('interceptors'), 7 | symTypes = nsPrefix('types'); 8 | 9 | function argsResolver(type) { 10 | return type[symTypes].map(function(t) { 11 | return instance(t); 12 | }); 13 | } 14 | 15 | function interceptorsOf(type) { 16 | if (!type[symInterceptors]) { 17 | type[symInterceptors] = []; 18 | } 19 | 20 | return type[symInterceptors]; 21 | } 22 | 23 | function intercept(obj, interceptors) { 24 | return interceptors.reduce(function(newInstance, interceptor) { 25 | return interceptor(newInstance); 26 | }, obj); 27 | } 28 | 29 | function defaultProvider(type) { 30 | var interceptors = interceptorsOf(type); 31 | 32 | if (type[symTypes]) { 33 | return function() { 34 | var obj = new (Function.prototype.bind.apply(type, [null].concat(argsResolver(type)))); 35 | 36 | if (interceptors.length > 0) { 37 | obj = intercept(obj, interceptors); 38 | } 39 | 40 | return obj; 41 | }; 42 | } 43 | return function() { 44 | var obj = new type(); 45 | 46 | if (interceptors.length > 0) { 47 | obj = intercept(obj, interceptors); 48 | } 49 | 50 | return obj; 51 | }; 52 | } 53 | 54 | export function provider(type) { 55 | if (!type[symProvider]) { 56 | type[symProvider] = defaultProvider(type); 57 | } 58 | return type[symProvider]; 59 | } 60 | 61 | export function provide(type, factory) { 62 | return { 63 | as: function(factory) { 64 | type[symProvider] = factory; 65 | } 66 | }; 67 | } 68 | 69 | export function singleton(type) { 70 | type[symProvider] = function() { 71 | var instance = defaultProvider(type)(); 72 | 73 | type[symProvider] = function() { 74 | return instance; 75 | }; 76 | 77 | return instance; 78 | }; 79 | } 80 | 81 | export function immutable(type) { 82 | interceptorsOf(type).push(function(newInstance) { 83 | return Object.freeze(newInstance); 84 | }); 85 | } 86 | 87 | export function inject() { 88 | var types = []; 89 | for(var i = 0; i < arguments.length; i++) { 90 | types[i] = arguments[i]; 91 | } 92 | 93 | return function(target) { 94 | if (target[symTypes]) { 95 | target[symTypes] = types.concat(target[symTypes]); 96 | } else { 97 | target[symTypes] = types; 98 | } 99 | }; 100 | } 101 | 102 | export function instance(type) { 103 | return provider(type)(); 104 | } 105 | 106 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple Dependency Injection with ES Decorators 2 | 3 | 4 | [![Build Status](https://travis-ci.org/lgvo/di-decorators.svg?branch=master)](https://travis-ci.org/lgvo/di-decorators) 5 | [![Coverage Status](https://coveralls.io/repos/lgvo/di-decorators/badge.svg?branch=master&service=github)](https://coveralls.io/github/lgvo/di-decorators?branch=master) 6 | [![npm version](https://badge.fury.io/js/di-decorators.svg)](http://badge.fury.io/js/di-decorators) 7 | [![Code Climate](https://codeclimate.com/github/lgvo/di-decorators/badges/gpa.svg)](https://codeclimate.com/github/lgvo/di-decorators) 8 | [![npm](https://img.shields.io/npm/dm/di-decorators.svg)](https://www.npmjs.com/package/di-decorators) 9 | [![Join the chat at https://gitter.im/lgvo/di-decorators](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/lgvo/di-decorators?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 10 | 11 | 12 | This project is a easy to use little dependency injection framework on top of ES Decorators. 13 | The basic idea is to have a easy way to declare dependencies with ES decorators. 14 | 15 | **Please take the time to star the project if you like it! "npm star di-decorators" and also on github [di-decorators](https://github.com/lgvo/di-decorators).** 16 | 17 | ## Installation 18 | 19 | ```sh 20 | $ npm install --save di-decorators 21 | ``` 22 | 23 | ## Usage 24 | 25 | ### Babel Config 26 | Yout need a ES.next transpiler to run di-decorators, in that case Babel. 27 | ```sh 28 | $ npm install --global babel 29 | ``` 30 | 31 | Right now to use decorators with Babel you need to configure it with stage 1. 32 | Simple add a ".babelrc" file on the root of your project: 33 | ```javascript 34 | {"stage": 1} 35 | ``` 36 | 37 | For more details on how to use babel: [https://babeljs.io](https://babeljs.io) 38 | 39 | 40 | ### Inject and Instance 41 | 42 | ```javascript 43 | import {instance, inject} from 'di-decorators'; 44 | import {ClassToBeInjected} from './somePackage'; 45 | 46 | @inject(ClassToBeInjected) 47 | class MyClass { 48 | 49 | constructor(injected) { 50 | this.dependency = injected; 51 | } 52 | } 53 | 54 | 55 | var myObject = instance(MyClass); // create a instance of MyClass with the dependencies 56 | myObject.dependency; // will be a instance of ClassToBeInjected 57 | ``` 58 | 59 | You can inject any class, by default a new instance will be created. 60 | In the last example the call to "instance(MyClass)" will be the same as "new MyClass(new ClassToBeInjected())". 61 | 62 | ### Immutable 63 | 64 | ```javascript 65 | import {instance, immutable} from 'di-decorators'; 66 | 67 | @immutable 68 | class CannotChange { 69 | constructor() { 70 | this.value = 1; 71 | } 72 | } 73 | 74 | var obj = instance(CannotChange); 75 | 76 | obj.value; // 1 77 | Object.isFrozen(obj); // true 78 | 79 | obj.value = 2; // Throws a TypeError: Cannot assign to read only property 'value' 80 | 81 | ``` 82 | 83 | You can mark a class as immutable so the instance will be frozen. 84 | 85 | ### Singleton 86 | 87 | ```javascript 88 | import {instance, inject, singleton} from 'di-decorators'; 89 | 90 | @singleton 91 | class TheOne { 92 | 93 | } 94 | 95 | @inject(TheOne) 96 | class A { 97 | constructor(one) { 98 | this.one = one; 99 | } 100 | } 101 | 102 | @inject(TheOne) 103 | class B { 104 | constructor(one) { 105 | this.one = one; 106 | } 107 | } 108 | 109 | var a = instance(A), 110 | b = instance(B); 111 | 112 | a.one === b.one; // will be true, the instance is the same 113 | a.one === instace(TheOne); // also true 114 | ``` 115 | 116 | If you want to have only one instance of some class you can use the @singleton decorator, that way every time you inject the same instance of the class. 117 | 118 | ### Inheritance 119 | 120 | ```javascript 121 | import {instance, inject} from 'di-decorators'; 122 | 123 | class Hello { 124 | message() { 125 | return "Hello"; 126 | } 127 | } 128 | 129 | @inject(Hello) 130 | class Super { 131 | constructor(hello) { 132 | this.hello = hello; 133 | } 134 | } 135 | 136 | class World { 137 | message() { 138 | return "World"; 139 | } 140 | } 141 | 142 | @inject(World) 143 | class MyClass extends Super { 144 | constructor(world, hello) { 145 | super(hello); 146 | this.world = world; 147 | } 148 | 149 | helloWorld() { 150 | return this.hello.message() + ' ' + 151 | this.world.message() + '!'; 152 | } 153 | } 154 | 155 | instance(MyClass).helloWorld(); // will be the string 'Hello World!' 156 | 157 | ``` 158 | 159 | So how it works? Basically when you extend a class with dependency injections we add theses dependencies to the current class so you can pass to the super constructor. 160 | 161 | 162 | The ideal way to do that is using rest parameters, so you can add more dependencies to the super class without worry to change everyone that extends it. 163 | 164 | Se the example bellow: 165 | ```javascript 166 | 167 | class A {} 168 | class B {} 169 | 170 | @inject(A, B) 171 | class Super { 172 | constructor(a, b) { 173 | this.a = a; 174 | this.b = b; 175 | } 176 | } 177 | 178 | class C {} 179 | 180 | @inject(C) 181 | class MyClass extends Super { 182 | constructor(c, ...args) { 183 | super(...args); 184 | this.c= c; 185 | } 186 | } 187 | ``` 188 | 189 | 190 | ### Defining your own provider. 191 | 192 | ```javascript 193 | import {instance, provide} from 'di-decorators'; 194 | 195 | class MyClass { 196 | constructor(name) { 197 | this.name = name; 198 | } 199 | } 200 | 201 | provide(MyClass).as(function() { 202 | return new MyClass('provider'); 203 | }); 204 | 205 | instance(MyClass).name; // will be the 'provider' string; 206 | ``` 207 | 208 | You can use provide to define how to create the instance. 209 | 210 | ## See Also 211 | * [restful-express](https://github.com/lgvo/restful-express) declarative way to define Express routers using decorators. 212 | * [express-promise-wrapper](https://github.com/lgvo/express-promise-wrapper) simple wrapper to to transform promise results into express functions. 213 | 214 | ## Contributing 215 | * Pull Requests are welcome! 216 | * Feel free to fork, and if you are planning to add more features please open a issue so we can discuss about. 217 | * Mind the test coverage and code complexity, if you can do it with TDD probably will come with both. 218 | * Try to use only ES5 in the core lib. 219 | 220 | ## License 221 | [MIT](LICENSE) 222 | -------------------------------------------------------------------------------- /di-es6.spec.js: -------------------------------------------------------------------------------- 1 | import chai from 'chai'; 2 | import {proxy, immutable, provide, provider, singleton, inject, instance} from './di'; 3 | 4 | const expect = chai.expect; 5 | 6 | describe('Provide', function() { 7 | 8 | it('should create a function provider for a class', function() { 9 | 10 | class Test { 11 | constructor(name) { 12 | this.name = name; 13 | } 14 | } 15 | 16 | provide(Test).as(() => new Test('factory')); 17 | 18 | expect(provider(Test)).to.exist; 19 | expect(instance(Test).name).to.equal('factory'); 20 | }); 21 | 22 | }); 23 | 24 | describe('Inject', function() { 25 | 26 | it('should inject dependencies', function() { 27 | 28 | class A { 29 | constructor() { 30 | this.name = 'a'; 31 | } 32 | } 33 | 34 | @inject(A) 35 | class B { 36 | constructor(a) { 37 | this.injected = a.name === 'a'; 38 | } 39 | } 40 | 41 | @inject(A, B) 42 | class C { 43 | constructor(a, b) { 44 | this.injected = a.name === 'a' && b.injected; 45 | } 46 | } 47 | 48 | expect(instance(B).injected).to.be.true; 49 | expect(instance(C).injected).to.be.true; 50 | 51 | }); 52 | 53 | }); 54 | 55 | describe('Singleton', function() { 56 | 57 | it('should only have one instance', function() { 58 | @singleton 59 | class Single { 60 | constructor() { 61 | this.name = 'singleton'; 62 | } 63 | 64 | } 65 | 66 | class Test { 67 | 68 | } 69 | 70 | expect(instance(Single)).to.equal(instance(Single)); 71 | expect(instance(Test)).not.to.equal(instance(Test)); 72 | expect(instance(Single).name).to.equal('singleton'); 73 | 74 | }); 75 | 76 | }); 77 | 78 | describe('Immutable', function() { 79 | 80 | it('should create immutable objects', function() { 81 | @immutable 82 | class CantChange { 83 | constructor() { 84 | this.name = 'original'; 85 | } 86 | } 87 | 88 | // direct wont be fronzen 89 | expect(Object.isFrozen(new CantChange())).to.be.false; 90 | 91 | // using 92 | expect(Object.isFrozen(instance(CantChange))).to.be.true; 93 | 94 | }); 95 | 96 | it('should create immutable objects (with dependencies)', function() { 97 | 98 | class Dependency { 99 | constructor() { 100 | this.name = 'dep'; 101 | } 102 | } 103 | 104 | @immutable 105 | @inject(Dependency) 106 | class CantChange { 107 | constructor(dep) { 108 | this.dep = dep; 109 | this.name = 'original'; 110 | } 111 | } 112 | 113 | // direct wont be fronzen 114 | expect(Object.isFrozen(new CantChange())).to.be.false; 115 | 116 | // using 117 | expect(Object.isFrozen(instance(CantChange))).to.be.true; 118 | 119 | expect(instance(CantChange).dep.name).to.equal('dep'); 120 | 121 | }); 122 | 123 | it('should work as a immutable dependency', function() { 124 | @immutable 125 | class Dependency { 126 | constructor() { 127 | this.name = 'dep'; 128 | } 129 | } 130 | 131 | @inject(Dependency) 132 | class Test { 133 | constructor(dep) { 134 | this.dep = dep; 135 | } 136 | } 137 | 138 | expect(Object.isFrozen(instance(Test).dep)).to.be.true; 139 | 140 | }); 141 | }); 142 | 143 | describe('Inheritance', function() { 144 | it('should support for use the Super dependencies', function() { 145 | var queue = []; 146 | 147 | class Publisher { 148 | send(message) { 149 | queue.push(message); 150 | } 151 | } 152 | 153 | class Subscriber { 154 | consume() { 155 | return queue.pop(); 156 | } 157 | } 158 | 159 | @inject(Publisher) 160 | class Super { 161 | constructor(publisher) { 162 | this.publisher = publisher; 163 | expect(publisher instanceof Publisher).to.be.true; 164 | } 165 | 166 | send(message) { 167 | this.publisher.send(message); 168 | } 169 | 170 | } 171 | 172 | @inject(Subscriber) 173 | class MyClass extends Super { 174 | constructor(subscriber, publisher) { 175 | super(publisher); 176 | this.subscriber = subscriber; 177 | expect(subscriber instanceof Subscriber).to.be.true; 178 | } 179 | 180 | publish(message) { 181 | super.send(message); 182 | } 183 | 184 | consume() { 185 | return this.subscriber.consume(); 186 | } 187 | } 188 | 189 | var myObj = instance(MyClass); 190 | myObj.publish('test'); 191 | 192 | expect(myObj.consume()).to.equal('test'); 193 | expect(queue).to.be.empty; 194 | }); 195 | 196 | it('should support multiple dependencies', function() { 197 | 198 | class A {} 199 | class B {} 200 | class C {} 201 | 202 | @inject(A,B,C) 203 | class ABC { 204 | constructor(a,b,c) { 205 | this.a = a; 206 | this.b = b; 207 | this.c = c; 208 | } 209 | } 210 | 211 | class D {} 212 | 213 | @inject(D) 214 | class MyClass extends ABC { 215 | constructor(d, ...args) { 216 | super(...args); 217 | this.d = d; 218 | } 219 | } 220 | 221 | var myObj = instance(MyClass); 222 | 223 | expect(myObj.a instanceof A).to.be.true; 224 | expect(myObj.b instanceof B).to.be.true; 225 | expect(myObj.c instanceof C).to.be.true; 226 | expect(myObj.d instanceof D).to.be.true; 227 | }); 228 | 229 | it('should support more than 2 levels', function() { 230 | 231 | var count = 0; 232 | 233 | class A {} 234 | class B {} 235 | class C {} 236 | 237 | @inject(A) 238 | class Grandfather { 239 | constructor(a) { 240 | expect(a instanceof A).to.be.true; 241 | count++; 242 | } 243 | 244 | } 245 | 246 | @inject(B) 247 | class Father extends Grandfather { 248 | constructor(b, a) { 249 | super(a); 250 | expect(b instanceof B).to.be.true; 251 | count++; 252 | } 253 | 254 | } 255 | 256 | @inject(C) 257 | class Son extends Father{ 258 | constructor(c, b, a) { 259 | super(b, a); 260 | expect(c instanceof C).to.be.true; 261 | count++; 262 | } 263 | } 264 | 265 | instance(Son); 266 | 267 | expect(count).to.equal(3); 268 | 269 | }); 270 | 271 | }); 272 | --------------------------------------------------------------------------------