node.js Dependency Injection
Scale your node.js app with ease.
npm i hekdi
Basic usage:
// imported.module.jsconst createModule = ; { thisname = 'Dependency1'; } static get return 'LocalDependency'; { thisname = 'Dependency2'; thisd1 = d1; } moduleexports = ;
// main.module.jsconst createModule = ;const importedModule = ; static get return 'PublicDependency' 'Arr'; { console; } moduleexports =
// app.jsconst DI = ;const MainModule = ;const di = DI; di; const ctrl = di;// Dependency2 { name: 'Dependency2', d1: Dependency1 { name: 'Dependency1' } } [ 1, 2, 3 ]
Main concepts:
Top level API:
Top level api is DI
class that bootstraps main module and serves dependencies from it then.
const DI = ;const di = DI; di // creates new module from config di // register module as main one and resolve dependencies from it const dep = di // return dependency that was registered to bootstrapped module according to its strategy
Modularity:
DI provides modules as a structural unit of app.
declarations
array sets own dependencies of this module.exports
array tells what dependencies are available for other modulesimports
array will inject exported members from other module to this one
const createModule = ; ;// here 'LocalDependency' will be available for injection only for members of this module.
Strategies:
service
- each time a new instance will be created withnew
keyword.factory
- return the result of plain function call.singleton
- only one instance will be created.value
- just will be returned.constant
- the same asvalue
but can't be reassign.alias
- used to create an alias for some dependency.
Koa.js usage:
hekdi
can be integrated with koa.js.
The main concept of framework integration is monkey patching of functions that are responsible for requests handling.
While using koa hakdi monkey patches use
method.
Basic usage:
const Koa = ;const koaDI = ;const app = ; const moduleToBootstrap = name: 'MainModule' declarations: name: 'ctrl' strategy: 'singleton' value: SomeClass name: 'echo' strategy: 'value' value: async { ctxbody = ctxrequestbody; } exports: '*'; ;// now di is already bootstrapped and ready to work. // In koa app you can reach di as `app.context.di`// In di you can get koa app as `App` dependency.app; app; // you can reach some function without class creation by passing only action// to `use` method app; app
Usage with router
While using router the story is almost the same:
'use strict'; const Koa = ;const Router = ;const bodyParser = ;const koaDI = ; const app = ;const router = ; const moduleToBootstrap = name: 'MainModule' declarations: name: 'ctrl' strategy: 'singleton' value: SomeClass name: 'echo' strategy: 'value' value: async { ctxbody = ctxrequestbody; } exports: '*'; ; app; router ; app ; app;