2.0.2 • Published 5 years ago

simple-dijs v2.0.2

Weekly downloads
3
License
ISC
Repository
github
Last release
5 years ago

SIMPLE-DIJS

Simple Javascript Dependency Injection Container (DI) like Pimple, well tested browser/node - ES6 Arrow Functions compatible

NOTE : this is V2. The V2 doesn't support callback anymore and can broke compatibity with old node versions in the future. Please use the v1 if you need to use callbacks or old node version.

npm npm

Installation

  • You can install from NPM
    npm install --save simple-dijs

Integration

    // NodeJs
    var Di = require('simple-dijs');
    // Web (just an example)
    ln -s node_modules/simple-dijs/dist/di.js public/lib/di.js
    // And minified : Only 4 K !
    ln -s node_modules/simple-dijs/dist/di.min.js public/lib/di.min.js
    <!-- Available global or ADM (requirejs), thanks to Browserify -->
    <script src="lib/di.js" type="text/javascript"></script>
    <!-- Exists di.min.js -->
    <script src="lib/di.min.js" type="text/javascript"></script>

Examples to use

    // Simple instanciation
    var di = new Di();
    // Also instanciation with services
    new Di({
        'database': function () { ... },
        'userCollection': function (di) { ... }
    });

    di.set('database', function () {
        return new Database();
    });

    di.set('userCollection', function (di) {
        return new UserCollection(di.get('database'));
    });

    // Or multiple services
    di.batchSet({ ..same than construct.. });

    // So, ...
    di.get('userCollection').find(1); // UserCollection instanciated now !
    di.get('userCollection').find(1); // The same UserCollection instance

    // If you want to factory instead of return the same object :
    di.set('userCollection', di.factory(function (di) {
        return new UserCollection(di.get('database'));
    }));

    // So, ...
    di.get('userCollection').find(1); // UserCollection instanciated now !
    di.get('userCollection').find(1); // Other UserCollection instance now, instanciated now !

    // You can store raw values
    di.set('port', 80);
    di.get('port'); // 80

    // Protect function you want to register raw :
    di.set('math.add', di.protected(function (a, b) {
        return a + b;
    }));

    // New feature in v2 ! You can inject your dependencies in arguments

    di.set('database', function (config, logger) { // You have declared config and logger
        return new Database(config.database, logger);
    });

    // Or with ES6 Arrow Functions

    di.set('database', (config, logger) => new Database(config.database, logger) });

    // You cannot use callbacks anymore. Please see version 1.x

    // You can use promise (native or not)

    di.set('async', function () {
        return new Promise(/*Blabla*/);
    });

    di.get('async').then(function () {
        // ...
    });

    // You can chain the methods calls
    (new Di()).set(...).set(...);

Quality and license

  • A complete build is configured. Always green before release
  • Tests are written before code (TDD) : The what before the how
  • Uses the http://semver.org/ versionning
  • Please report issues and suggestions https://github.com/gallofeliz/simple-dijs/issues
  • Please watch the github project if you use GitHub watchers
  • Please star the github project if you like GitHub stars

API Reference

Di

Kind: global class

-

new Di(values)

Create a new Container

ParamTypeDescription
valuesObject.<string, *>Values to set on construction (eqiv batchSet batchSet)

Example

var di = new Di()

Example

var di = new Di({
  id1: value1,
  id2: value2
})

-

di.batchSet(values) ⇒ Di

Multiple set values

Kind: instance method of Di
Returns: Di - himself
Throws:

  • Error If values is not provided or not Object
ParamTypeDescription
valuesObject.<string, *>Values to set

Example

di.batchset({
   id1: value1,
   id2: value2
})

-

di.factory(func) ⇒ function

Create a factory function

Kind: instance method of Di
Returns: function - The same function
Throws:

  • Error Missing or incorrect argument
  • Error Protected function

See: Di#set

ParamTypeDescription
funcfunctionThe function to factory

Example

di.set('token', di.factory(function () {
  return new Token();
}))

-

di.get(id, callback) ⇒ undefined

Get a value asynchronously with callback (registered with callback)

Kind: instance method of Di
Throws:

  • Error Missing or incorrect argument
  • Error Missing value (not registered)
  • Error Unexpected callback for no-callback registered value
  • Error Invalid callback
ParamTypeDescription
idstringThe value id
callbackfunctionThe callback

Example

di.get('database', function (err, database) {
   if (err) {
       // ...
   }
   database.find(userId);
})

-

di.get(id) ⇒ *

Get a value synchronously

Kind: instance method of Di
Returns: * - The value
Throws:

  • Error Missing or incorrect argument
  • Error Missing value (not registered)
  • Error Missing callback for callback-registered value
ParamTypeDescription
idstringThe value id

Example

di.get('database').find(userId)

-

di.has(id) ⇒ boolean

Check that the container owns the provided id

Kind: instance method of Di
Returns: boolean - If id is owned by the container

ParamTypeDescription
idstringId to check

Example

di.has('database') || di.set('database', ...)

-

di.keys() ⇒ Array.<string>

Get all the ids

Kind: instance method of Di
Returns: Array.<string> - the ids

-

di.protect(func) ⇒ function

Protect a function to store as raw

Kind: instance method of Di
Returns: function - The same function
Throws:

  • Error Missing or incorrect argument
  • Error Factory function

See: Di#set

ParamTypeDescription
funcfunctionThe function to factory

Example

di.set('math.add', di.protect(function (a, b) {
  return a + b;
}))

-

di.register()

Deprecated

Kind: instance method of Di

-

di.remove(id) ⇒ Di

Remove a value

Kind: instance method of Di
Returns: Di - himself
Throws:

  • Error Missing or incorrect argument
  • Error Missing value (not registered)
ParamTypeDescription
idstringThe value id

Example

di.remove('database')

-

di.set(id, funcOrValue) ⇒ Di

Set a value in the container. The registered value is by default the returned value.

In case you use a function to factory your value :

  • you can use the first injected argument that is the current Di instance.
  • you can register your value (for example for asynchronous) by declaring and calling the second possible argument "callback", as a normal node callback.

Kind: instance method of Di
Summary: Set a value in the container, synchronously or asynchronously
Returns: Di - himself
Throws:

  • Error if missing or incorrect arguments
  • Error if Id is already registered
ParamTypeDescription
idstringThe id of value
funcOrValue*The value

Example (Set a raw value)

di.set('color', '#ff0000')

Example (Set a building function (value with be cached after first call))

di.set('database', function (di) {
  return new Database(di.get('database_url'));
})

Example (Set a factory function (value will be factoryed each call))

di.set('token', di.factory(function () {
  return new Token();
}))

Example (Set a building function that returns a promise)

di.set('config', function () {
  return fsPromise.readFile('config.json');
})

Example (Set a building function that use callback for async)

di.set('config', function (di, callback) {
  fs.readFile('config.json', callback);
})

-

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

6 years ago

1.11.0

6 years ago

1.10.0

7 years ago

1.8.0

8 years ago

1.7.0

8 years ago

1.6.0

8 years ago

1.5.0

8 years ago

1.3.0

8 years ago

1.2.0

8 years ago

1.1.1

8 years ago

1.0.3

8 years ago

1.0.2

9 years ago

1.0.1

9 years ago

1.0.0

9 years ago