Last active
November 22, 2015 18:56
-
-
Save kiasaki/95b96d4d1710cfc5abb4 to your computer and use it in GitHub Desktop.
Node.js architecture blog post (container.js)
This file contains hidden or 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
import R from 'ramda'; | |
export default class Container { | |
constructor() { | |
this.contents = {}; | |
} | |
get(name) { | |
if (!(name in this.contents)) { | |
throw Error('Container has nothing registered for key ' + name); | |
} | |
return this.contents[name]; | |
} | |
set(name, instance) { | |
this.contents[name] = instance; | |
} | |
create(klass) { | |
if (!('length' in klass.dependencies)) { | |
throw new Error('Invariant: container can\'t resolve a class without dependencies'); | |
} | |
var dependencies = R.map(function(dependencyName) { | |
return this.get(dependencyName); | |
}.bind(this), klass.dependencies); | |
return applyToConstructor(klass, dependencies) | |
} | |
load(klass) { | |
if (typeof klass.dependencyName !== 'string') { | |
throw new Error('Invariant: container can\'t resolve a class without a name'); | |
} | |
this.set(klass.dependencyName, this.create(klass)); | |
} | |
unset(name) { | |
delete this.contents[name] | |
} | |
reset() { | |
this.contents = {}; | |
} | |
} | |
function applyToConstructor(constructor, args) { | |
var newObj = Object.create(constructor.prototype); | |
var constructorReturn = constructor.apply(newObj, args); | |
// Some constructors return a value; let's make sure we use it! | |
return constructorReturn !== undefined ? constructorReturn : newObj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment