Last active
June 24, 2017 16:14
-
-
Save sota1235/47daaf29f3b883498b54882d7addd070 to your computer and use it in GitHub Desktop.
Simple DI Container with flow
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
| /** | |
| * @flow | |
| * @fileoverview Container for getting instance. | |
| */ | |
| type InstanceInfo = { | |
| strict: boolean, | |
| closuer: Function, | |
| }; | |
| type RegistedInstance = { | |
| [string]: InstanceInfo, | |
| }; | |
| const isProduction = process.env.NODE_ENV === 'production'; | |
| class Container { | |
| container: RegistedInstance; | |
| get<T>(modulePath: string): T { | |
| const value: InstanceInfo = this.container[modulePath]; | |
| if (!value) { | |
| throw new Error(`Instance not found - ${modulePath}`); | |
| } | |
| const instance: T = value.closuer(this); | |
| if (value.strict && isProduction) { | |
| const Target = require(modulePath); // eslint-disable-line global-require, import/no-dynamic-require | |
| if (!(instance instanceof Target)) { | |
| throw new Error(`modulePath does not match instance type - ${modulePath}`); | |
| } | |
| } | |
| return instance; | |
| } | |
| set(modulePath: string, closuer: Function, strict: boolean = false): Container { | |
| this.container = Object.assign({}, this.container, { | |
| [modulePath]: { | |
| strict, | |
| closuer, | |
| }, | |
| }); | |
| return this; | |
| } | |
| dump() { | |
| console.log(this.container); | |
| } | |
| } | |
| // Export as singleton instance | |
| export default new Container(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment