Dependency Injection in JAVASCRIPT (Awilix decorator)
Aliakbar Salehi
Posted on June 28, 2020
SOLID is one of the important factors to have a clean and maintainable code.
one of the most popular with an easy learning curve for DI in javascript world is awilix.
there are also other popular alternatives such as inverify, but if you go to their documentation it is really huge.
in overall, I don't want to compare them in this article , just I try to share my simple code which could be helpful for you if you decide to work with awilix
.
const getKeyName = (x: string | Function) => typeof x === 'string' ? x : (<Function>x).name
type dependencyType = 'request' | 'response' | 'nextFunction' | 'logger'
export function InjectDependency(
...dependencies: Array<
dependencyType
| Function
| Record<string, dependencyType | Function>
>
) {
return <T extends { new(...args: any[]): {} }>(constructor: T) => {
return ({
[`__${constructor.name}__injected`]: class extends constructor {
constructor(...args: any[]) {
if (args.length) {
const proxy = args[0]
super(proxy)
for (let d of dependencies) {
switch (typeof d) {
case 'object':
Object.keys(d).forEach(key => {
this[key] = proxy[getKeyName(d[key])]
})
break
default:
const key = getKeyName(d)
this[key] = proxy[key]
break
}
}
}
}
}
})[`__${constructor.name}__injected`]
}
}
This code is a simple decorator on express js, you can easily get your dependencies inside an object without writing extra code.
I will try to explain it in next posts.
💖 💪 🙅 🚩
Aliakbar Salehi
Posted on June 28, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.