simple-ioc
Simple-ioc is a module for simple inversion of control for node.js. Main features are:
- Easy dependency injection without special syntax - in most cases modules can be used without simple-ioc.
- Easy exchangeability of components - settings can determine which components that should be used in different environments.
- Automatic asynchronous resolving - components are only resolved when all dependencies are resolved
Installation
Simple-ioc is installed from npm.
npm install simple-ioc
Basic usage and simple example
The following is a simple example of how to use simple-ioc
Example of usage
// ./lib/store.jsmodule { databaseAdapter;};
// ./lib/module1.jsmodule { pub { store; };};
// ./index.jsmoduleexports =
Additionally every container has the following pre-registered components, which makes them virtually reserved as well:
#### pub A module can return its instance in two ways, either by creating the instance itself and returing it (or by using it as the argument asynchronously to the callback, see section [`callback`](#iocCallback) for more information) or by depending on `pub` and attaching properties to this object.The use of pub
is optional. It might be handy but it complicates using the module without the ioc, so use it only when you feel comfortable with simple-ioc.
Example:
module { var pub = {}; pub {}; return pub;};
is equivalent to:
module { pub {};};
If using pub
the module is more complex to resolve without the ioc. It can still be done by doing something like this:
var resolved = {};myModule( resolved );
Example:
var container = ;
Example:
var container = ;
Note that this this is not implemented yet, but might be a good idea to use.
Example:
var container = ;
Documentation
getContainer()
setSettings( settings1, settings2, settings3, ... )
getSettings()
useLogWriter( resolvedWriter )
registerResolved( name, instance )
registerInjectable( name, fn )
mock( name, properties )
registerGlobalWrappersFromSettings( settingsKey )
autoRegisterPath( relativePath, [omitFileIocComments], [omitFileLengthLogging] )
resolve( name, callback )
registerIocSettings( name )
registerIocLog( name )
resolveAllAndInject( fn )
injectAfterResolveAll( fn )
inject( fn, [callback] )
registerResolvedIfSetting( settingKey, name, instance )
registerInjectableIfSetting( settingKey, name, fn )
autoRegisterPathInSetting( settingKey )
removeRegistered( name )
export( name )
fatal( message, [ data ] )
error( message, [ data ] )
warning( message, [ data ] )
info( message, [ data ] )
debug( message, [ data ] )
trace( message, [ data ] )
getEntries( [componentName] )
reset()
The main function of the ioc is to create containers, but it also has a built-in log and settings.
### getContainer() Creates a new container.
Arguments
None.
Returns
A new container.
Remarks
The ioc, the container itself and errRerouter is registered automaticaly to the new container.
Example
var container =
### setSettings( settings1, settings2, settings3, ... ) Sets the settings the ioc will read, initially the sttings will have a log-property, see section [log](#log) for more information about the built-in logger.
Arguments
Variable amount of objects with settings, the settings will be merged with the existing settings.
Returns
The ioc.
Remarks
The ioc has 5 built-in output-writers, these are
- consoleJson - More or less console.log( JSON.stringify( logObject ) )
- bunyanJson - Same idea of
consoleJson
, but you can usebunyan
command to read pretty printed errors as an human. - consoleReadable - Logs in a readable format, with some coloring of level
- devNull - writes nothing
- memoryJson - writes to memory, which is searchable afterwards. This should never be used in production, only in tests.
The default settings are:
{
log: {
level: 0,
includeEnvironmentVariables: { env: 'NODE_ENV' },
output: 'devNull'
}
}
Example
;/*will result in the following settings{ log: { level: 3, includeEnvironmentVariables: { env: 'NODE_ENV' }, output: 'consoleReadable' }}*/
Bunyan Example
node-bunyan is a medium-complex logging solution, integration in simple-ioc
is really minimal, and completely optional.
To use the bunyan writer you have to add bunyan
to your project dependencies.
;
Then you can pipe the output of your program to bunyan
command for pretty-print.
### getSettings() Gets the settings the ioc uses. See [registerIocSettings](#registerIocSettings) how to register settings in a container for injection.
Arguments
None.
Returns
The registered settings
Remarks
Normally this function is not used, instead settings are injected, but might be useful for debugging.
Example
;/* Will return{ log: { level: 0, includeEnvironmentVariables: { env: 'NODE_ENV' }, output: 'devNull' }, key: 'value'}*/
### useLogWriter( resolvedWriter ) The built-in logger (see [log](#log) for information) can also use a external output writer, it must implement the following functions:
- output( logObject ) - called on every log that is on a level that should be logged.
- getEntries( component ) - can be implemented, but should not be used in production.
- reset() - to reset the log entries.
Arguments
resolvedWriter
an object that implements at least output( logObject )
Returns
The ioc.
Remarks
None.
Example
;// Will only ouptut the level of the log (numeric) to the console.
container
Containers are the central part of the ioc, it stores and resolves components.
Note: All functions on the container returns the container itself.
### registerResolved( name, instance ) Registers a already resolved component to the container, e.g. external componens like "express".Arguments
- name - the identifying name of the component
- instance - the resolved instance
OR
- name - An object with key/value pairs reprecenting names/instances
Returns
The container
Remarks
Packages that have a simple name (without special characters, such as "-") and are possible to require within the current scope, does not need to be registered. For example, a module can have a dependency to "http" without it being registered. If a dependency exists to a component that is not registered, the container will try to require the name of the dependency and register it as a singleton if successful.
Example
var container = // Registers async ;
### registerInjectable( name, fn ) Registers an injectable component in the container, this method should normally be used when registering internal libraries which can use their own containers.
Arguments
- name - the identifying name of the component
- fn - the injectable function
OR
- name - An object with key/value pairs reprecenting names/instances
Returns
The container.
Remarks
Injectable functions has some reserved parameternames used by the ioc, these cannot be registered or used as normal dependencies. See Reserved dependencies for more information.
Example
var container = // Registers a singleton component that has an async setup and a function func1 as myComponent ;
### mock( name, properties ) Simple-ioc has a built-in mocking function, making it easier to mock modules with sync and async functions. Mock is not supposed to be used in production code, but rather in tests.
Arguments
name
name of the component to mockproperties
the properties to mock with functions, setting the default value of the mocked function
or
name
an object with key/value pairs reprecenting names/properties
Returns
The container
Remarks
Mocking of modules by using "mock" might not be totaly straight forward and cannot be used in every mocking situation. See the example how a possible way to use it and how to achieve the same result without using mock. The values of mocked functions can be changed by setting the properties later.
Mock checks when a function is invoked, if last parameter is a function it will treat is as an async function.
Example
;
### registerGlobalWrappersFromSettings( settingsKey ) Simple-ioc offers a method of wrapping methods in components of registered components. This can be useful if interception of calls are needed for tracking or debugging.
Arguments
settingsKey
the key in settings that specifies which components should be wrapped
Returns
The container.
Remarks
Wrappers can implement functions async
and or sync
, see example of usage. Wrapping is global and affects all containers in the ioc.
Example
;
### autoRegisterPath( relativePath, [omitFileIocComments], [omitFileLengthLogging] ) Register all files in the given path, using function name or, if not existing, the file name as name of component.
Arguments
relativePath
relative path or absolut path that th container will recursively look in.omitFileIocComments
(optinal) default false, if true, the container will not look for ioc specific comments.omitFileLengthLogging
(optional) default false, if true, no warnings for long files.
Returns
The container.
Remarks
Files that contains the followin comments will be handeled different by autoRegisterPath:
/* ioc:ignore */
- file will be ignored./* ioc:noresolve */
- file will be registered as resolved
If omitFileLengthLogging is not set, the ioc will info log if files exceed 100 lines and warning log if files exceed 200 lines.
Normally the ioc uses the name of the file as name of the component, but if the function is not anonymous, the name of the function is used.
In case the name of the component is hyphenated (some-component.js
), it will be camelCased when injected (someComponent
).
Example
// ./lib/module1.jsmodule { pubname = 'mod1';};
// ./lib/module2.jsmodule { pubname = module1name 'mod2' ;};
// ./lib/module3ButWithAnotherName.jsmodule { pubname = module2name 'mod3' ;};
// ./index.jsmoduleexports = ;
### resolve( name, callback )
Arguments
name
name of the component to resolvecallback( err, instance )
function to be called with the result of the resolve.
Returns
The container.
Remarks
Resolve can safely be used anytime, since it callbacks an error if the component is unresolvable.
Example
var assert = ; moduleexports =
### registerIocSettings( [ name ] ) Registers the ioc settings to the container with the specified name.
Arguments
name
the name settings should be registerd as, defaults to "settings"
Returns
The container.
Remarks
None.
Example
var assert = ; moduleexports = ;
### registerIocLog( [ name ] ) Registers the build-in ioc logger to the container with the specified name.
Arguments
name
the name settings should be registerd as, defaults to "log"
Returns
The container.
Remarks
None.
Example
var assert = ; moduleexports = ;
### resolveAllAndInject( fn ) Resolves all components that are unresolved and registered with singleton lifestyle. Finally the `fn` function is injected.
Arguments
fn
function to inject after all registered injectable singleton components are resolved.
Returns
The container.
Remarks
ResolveAllAndInject will log information about components that does not have any components that are depending on them.
Example
var assert = ; moduleexports = ; // Will have the following output: // module1 // module2 // injected
### inject( fn, [ callback ] ) Gives the possibility to inject anonymous functions
Arguments
fn
function to inject.callback
optional, called after the functions is injected.
Returns
The container
Remarks
None.
Example
var assert = ; moduleexports = ;
### injectAfterResolveAll( fn ) Specify a function that is injected after resolve all is complete, can be used in, for example, system tests.
Arguments
fn
function to inject
Returns
The container.
Remarks
None.
Example
// ./index.jsvar assert = ; moduleexports = ;
// ./tests/system/test.jsvar container = ;
### registerResolvedIfSetting ( settingKey, name, instance ) Registers an resolved component if settings indicates it should be registered. Used for example when a component only should be used in certain environments.
Arguments
- settingKey - the dot notated key in settings (true/false)
- name - the identifying name of the component
- fn - the resolved component
Returns
The container.
Remarks
None.
Example
var container = ; // Will register required component as resolved
### registerInjectableIfSetting( settingKey, name, fn ) Registers a injectable component if settings indicates it should be registered. Used for example when a component only should be used in certain environments.
Arguments
- settingKey - the dot notated key in settings (true/false)
- name - the identifying name of the component
- fn - the injectable function
Returns
The container.
Remarks
None.
Example
var container = ; // Will register required component as injectable
### autoRegisterPathInSetting( settingKey ) Auto registers path that is specified in the settings, can be used for example when different adapers are used in development and production.
Arguments
- settingKey - the dot notated key in settings that referes to the path
Returns
The container.
Remarks
None.
Example
var container = ; // Will auto register all files in the path '/myPath/adaper1'
### removeRegistered( name ) Removes an injectable unresolved component from the container, main purpose is to change behaviour in system-tests after an application is started with 'resolveAllAndInject'.
Arguments
- name - the identifying name of the component to remove from the container
Returns
The container.
Remarks
Only injectable components that has not yet been resolved can be removed.
Example
// ./index.jsvar assert = ; moduleexports = ;
// ./tests/system/test.jsvar container = ;
Arguments
- name - the identifying name of the component to export
Returns
An injectable functions with that callbacks the component
Remarks
None.
Example
// ./index.jsvar assert = ; moduleexports = ;
## log The ioc has a built in logger that can be used externaly as well. The logger builds a logObject that looks like this:
level: level message: message data: data component: parentName ...environment variables specified in the settings
In the log-settings you can specify envronment values that you would like to include in the log-objects
includeEnvironmentVariables: enviro: 'ENV_NAME' // Would include ENV_NAME as "enviro"
### fatal( message, [ data ] )
Arguments
message
log messagedata
optional dataobject that will be in the output
Returns
Undefined.
Remarks
After the log is written system.exit() is automatically called.
Example
log; // Application will exit
### error( message, [ data ] )
Arguments
message
log messagedata
optional dataobject that will be in the output
Returns
Undefined.
Remarks
None.
Example
log;
### warning( message, [ data ] )
Arguments
message
log messagedata
optional dataobject that will be in the output
Returns
Undefined.
Remarks
None.
Example
log;
### info( message, [ data ] )
Arguments
message
log messagedata
optional dataobject that will be in the output
Returns
Undefined.
Remarks
None.
Example
log;
### debug( message, [ data ] )
Arguments
message
log messagedata
optional dataobject that will be in the output
Returns
Undefined.
Remarks
None.
Example
log;
### trace( message, [ data ] )
Arguments
message
log messagedata
optional dataobject that will be in the output
Returns
Undefined.
Remarks
None.
Example
log;
### getEntries( [ componentName ] ) If the memoryJson writer is used it is possible to iterate through the logs that have been written. This might be useful in tests.
Arguments
componentName
optional, name of component to get logs from
Returns
Undefined.
Remarks
None.
Example
log;assert;
### reset() If the memoryJson writer is used it is possible to reset the log-store.
Arguments
None.
Returns
Undefined.
Remarks
None.
Example
log;log;assert;
## errRerouter( callback, successFn ) Simple ioc offers a small helper function to route errors to calling component, this component is optional to use, but might be handy in some situations.
Arguments
callback
the callback to send error tosuccessFn
function to call if first argument evaluates as false.
Returns
The rerouter
remarks
None.
Example
module { pub { someErrorThrowingAsyncComponent; };};
Is equivalent to
module { pub { someErrorThrowingAsyncComponent; };};