1.3.0 • Published 12 months ago

di-service v1.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

DI Service

DI Service

Really simple dependency injection solution for JavaScript

Features

  • Implements DI pattern
  • Do not impose any system architecture, may be introduced to any JavaScript project (FE and BE both)
  • Pure JavaScript implementation (+ TypeScript declaration file)
  • Zero dependencies
  • ES Module and CommonJS hybrid module

Example

Declare any class

class Settings {
    dbServer = process.ENV.DB_SERVER;
    dbUser = process.ENV.DB_USER;
    dbPassword = process.ENV.DB_PASSWORD; // don't do like this
}

module.exports = { Settings };

Use the class as a dependency

const { Settings } = require('./settings');
const { SERVICE_REQUIRE } = require('di-service');

class DBConnection {
    
    static [SERVICE_REQUIRE] = [Settings];
    
    constructor(settings) {        
        // settings -> instance of the Settings class
        this.settings = settings;
    }
}

module.exports = { DBConnection };

Get service instance

const { DIService } = require('di-service');
const { DBConnection } = require('./db-connection');

const services = new DIService();
const connection1 = await services.getInstance(DBConnection);
const connection2 = await services.getInstance(DBConnection);
console.log(connection1 === connection2); // -> true
console.log(connection1.settings === connection2.settings); // -> true
console.log(connection1.settings.constructor.name); // -> Settings

Used by

1.2.0

12 months ago

1.2.2

12 months ago

1.3.0

12 months ago

1.2.1

12 months ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.0

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago