DEV Community

Cover image for Dependency Injection in JAVASCRIPT (Awilix decorator)
Aliakbar Salehi
Aliakbar Salehi

Posted on • Edited on

2

Dependency Injection in JAVASCRIPT (Awilix decorator)

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay