@rafterjs/di-autoloader
TypeScript icon, indicating that this package has built-in type declarations

0.8.75 • Public • Published

A dependency injection autoloader

Build Status

A config driven autoloader for dependency injection.

Getting started

yarn add @rafterjs/di-autoloader

Example

Check out the files in ./example and ./test/fixtures

The autoloading config

// service-config.js

const servicesConfig = {
    config: {
        path: `${__dirname}/../test/mocks/test-config`,
        dependencies: []
    },
    testClass: {
        path: `${__dirname}/../test/mocks/test-class`,
        dependencies: [
            `config.foo.bar`,
            'testFunction'
        ]
    },
    testFunction: {
        path: `${__dirname}/../test/mocks/test-function`,
        dependencies: []
    }
};

export default servicesConfig;

Example class with DI

// test-class.js

class TestClass {
    // The dependencies will be injected via the constructor
    constructor(bar, testFunction) {
        this._bar = bar;
        this._testFunction = testFunction;
    }

    /**
     * @return {string}
     */
    getBar() {
        return this._bar;
    }

    /**
     * @return {Function}
     */
    getFunction() {
        return this._testFunction;
    }

    /**
     * @return {string}
     */
    getData() {
        return `here's some data`;
    }
}

export default TestClass;

Instantiating the DI container using the autoloader

import BoxDiAutoLoader from '../lib/box-di-autoloader';
import serviceConfig from './service-config';

const boxDiAutoLoader = new BoxDiAutoLoader(serviceConfig);
boxDiAutoLoader.load();

const testClass = boxDiAutoLoader.get('testClass');
console.log(testClass.getData());

Why use dependency injection (DI)?

DI is a well vetted programming pattern that encourages decoupling of services and allows you to maintain separation of concerns. This in turn means your code is more testable and maintainable.

Check out: http://tutorials.jenkov.com/dependency-injection/dependency-injection-benefits.html and https://stackoverflow.com/questions/130794/what-is-dependency-injection

Why should we use it in node?

Just because we have import or require doesn't mean we should forgo programming best practices. What import does is hardcode your dependencies, rather than making them configurable or reusable eg.

Say we have a DbService which currently uses MongoDb. In an import style your code would be something like:

import mongoose from 'mongoose';

class DbService {
    async connect(url) {
        return mongoose.connect(url);
    }

    async find(query, Model) {
        return mongoose.find(query, Model);
    }

    ...
}

But now your app has grown and you realise that the load on your DB is reducing application performance; you need to introduce a caching layer to reduce the load on the DB.

In our import scenario above that would require a bunch of rewriting at the DbService level. Instead if we had structured it like:

class DbService {
    constructor(dao) {
        this._dao = dao;
    }

    async connect(url) {
        return this._dao.connect(url);
    }

    async find(query, Model) {
        return this._dao.find(query, Model);
    }

    ...
}

We could now inject MongoDbCacheDao instead of injecting mongoose. This would handle the caching, and delegate through to Mongo if needed. The DbService doesn't care if it is cached or not; it is none of it's concern. eg

import crypto from 'crypto'; // NOTE: importing from the node standard lib is ok

class MongoDbCacheDao {
    constructor(dao) {
        this._dao = dao;
        this._cache = {};
    }

    async connect(url) {
        return this._dao.connect(url);
    }

    async find(query, Model) {
        const md5sum = crypto.createHash('md5');
        md5sum.update(
            JSON.stringify(query) +
            JSON.stringify(Model)
        );

        const cacheId =  md5sum.digest('hex');
        if (!this._cache[cacheId]) {
            this._cache[cacheId] = await this._dao.find(query, Model);
        }

        return this._cache[cacheId];
    }

    ...
}

So even though we have import/require in node, it is still valuable to separate concerns and use dependency injection. It will allow you to be much more flexible in the future and adapt to changes more quickly.

Why use an autoloader with DI

As your application grows, so too does your dependency graph. Handling all your dependencies manually becomes very tedious and you end up with lots of boilerplate code in the form of factories. Instead, when using an autoloader, you maintain your dependencies in a simple config file and you only need to create factories in rare circumstances when class/function instantiation is much more complex.

Overall, this means less code to write and maintain, which means less complexity and faster time to market.

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
0.8.750latest

Version History

VersionDownloads (Last 7 Days)Published
0.8.750
0.8.740
0.8.731
0.8.720
0.8.710
0.8.700
0.8.690
0.8.680
0.8.670
0.8.660
0.8.650
0.8.640
0.8.630
0.8.620
0.8.610
0.8.600
0.8.590
0.8.580
0.8.570
0.8.560
0.8.550
0.8.540
0.8.530
0.8.520
0.8.510
0.8.500
0.8.490
0.8.480
0.8.470
0.8.461
0.8.450
0.8.440
0.8.430
0.8.420
0.8.410
0.8.401
0.8.390
0.8.370
0.8.360
0.8.350
0.8.340
0.8.330
0.8.320
0.8.32-alpha.00
0.8.310
0.8.300
0.8.290
0.8.280
0.8.270
0.8.260
0.8.250
0.8.240
0.8.230
0.8.220
0.8.210
0.8.200
0.8.190
0.8.180
0.8.170
0.8.160
0.8.150
0.8.140
0.8.130
0.8.120
0.8.110
0.8.100
0.8.90
0.8.80
0.8.70
0.8.60
0.8.50
0.8.40
0.8.30
0.8.20
0.8.10
0.7.10
0.7.00
0.7.0-alpha.60
0.7.0-alpha.30
0.7.0-alpha.20
0.7.0-alpha.01
0.6.00
0.5.1-alpha.10
0.5.1-alpha.00
0.5.00
0.4.2-alpha.40
0.4.2-alpha.30
0.4.2-alpha.20
0.4.2-alpha.10
0.4.2-alpha.00
0.4.10
0.4.00
0.3.10
0.3.00
0.2.70
0.2.60
0.2.50

Package Sidebar

Install

npm i @rafterjs/di-autoloader

Weekly Downloads

4

Version

0.8.75

License

GPL-3.0-or-later

Unpacked Size

102 kB

Total Files

39

Last publish

Collaborators

  • crimsonronin