npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

dijs

v0.2.1

Published

Asynchronous dependency injection framework for Node.js and browser environments

Downloads

54

Readme

dijs

dijs is a dependency injection framework for Node.js and browser environments.

It is inspired by AngularJS 1.x and allows to choose between synchronous and asynchronous (using callbacks and promises) resolution patterns in an non-opinionated way.

Featured on DailyJS.

Example

  const Di = require('dijs');

  class TestClass {
    constructor (PI, RAD_TO_DEG) {
      this.PI = PI;
      this.RAD_TO_DEG = RAD_TO_DEG;
    }

    deg (value) {
      return value * this.RAD_TO_DEG;
    }
  }

  // Initialize a new dijs instance. By default, this will use "CallbackMethod",
  // thus the first argument is "null" (instead providing another method).
  // The $provide and $resolve method expect callback functions.

  let instance = new Di(null)
  // Provides a constant
  .$provideValue('PI', Math.PI)
  // Providing a constant using dependencies
  .$provide('RAD_TO_DEG', (PI, callback) => callback(null, (180 / PI)))
  .$resolve((err) => {
    if (err) {
      throw err;
    }
    let AnnotatedTestClass = instance.$annotate(TestClass);
    let a = new AnnotatedTestClass();

    // logs 180
    console.log(a.deg(Math.PI));
  });

Options

assign

By default, all provided values are being set on the dijs instance. This behavior can be turned off:

  const Di = require('dijs');
  let d = new Di(null, 'Math', { assign : false });

  d.$provide('PI', function (callback) {
    callback(null, Math.PI);
  });
  d.$resolve(function (err) {
    if (err) {
      throw err;
    }
    console.log(`d.PI is undefined`, d.PI === undefined);
    console.log(`d.$get("PI") equals Math.PI`, d.$get('PI') === Math.PI);
  });
});

Usage

new Di(Method, name, options)

Returns a new dijs instance with the given method (CallbackMethod is the default one).

Instance methods

$annotate(classFn)

Returns a class which will be initialized with the dependencies stated in classFn's constructor. When classFn is a function, its parameters are being resolved to matching dependencies.

This method must called after $resolve().

$get(id)

Returns the (previously provided) sub-module specified by a dot-delimited id.

$inject(arg)

Calls a function with (already-provided) dependencies. It is required to call $resolve beforehand.

Dependant on the current resolution method, this function is synchronous or asynchronous

$provide(key, object, passthrough)

Provides a module in the namespace with the given key.

If passthrough is set, the object will be just passed through, no dependencies are looked up this way.

$provideValue(key, object)

Provides a value in the namespace with the given key (shortcut for $provide using passthrough).

$resolve()

Resolves the dependency graph.

This method might take a callback function (in case of the default CallbackMethod) or return a promise with PromiseMethod.

$set(id, value)

Sets a value in the namespace, specified by a dot-delimited path.

Resolution methods

By default, dijs uses the asynchronous CallbackMethod in order to resolve dependencies. Require them as follwing:

const Di = require('dijs');
const SyncMethod = require('dijs/methods/sync');
const PromiseMethod = require('dijs/methods/promise');

CallbackMethod

Asynchronous providing and resolving dependencies using Node.js-style callback functions.

It is expected that the last parameter of your callback functions is called "callback", "cb" or "next".

This function takes an error (or a falsy value like null) as first argument. The second argument should be the provided value.

  let d = new Di();
  d.$provide('PI', (callback) => { // alternative names: cb or next
    callback(null, Math.PI);
  });

  d.$resolve((err) => {
    if (err) {
      return done(err);
    }
    assert.equal(d.PI, Math.PI);
    done();
  });

PromiseMethod

Provides and resolves dependencies using the ES2015 Promise API.

  let d = new Di();
  d.$provide('PI', Promise.resolve(Math.PI));
  d.$provide('2PI', (PI) => Promise.resolve(2 * Math.PI));
  d.$resolve().then(() => {
    assert.equal(d['2PI'], 2 * Math.PI);
    done();
  }, (err) => {
    done(err);
  });

SyncMethod

Synchronous way to provide and resolve depdencies.

  let d = new Di(SyncMethod);
  d.$provide('PI', Math.PI);
  d.$provide('2PI', (PI) => 2 * Math.PI);
  d.$resolve();
  assert.equal(d['2PI'], 2 * Math.PI);

Reference

Notation

If you don't pass a value through, you can choose between the function and the array notation to describe the module's dependencies. In any case, you will need to pass a function whose return value gets stored in the namespace. Its parameters describe its dependencies.

function notation

To describe a dependency, you can pass a function whose parameters declare the other modules on which it should depend.

Note: You cannot inject dot-delimited dependencies with this notation.

  var mod = new Di();
  mod.$provide('Pi',Math.PI, true);
  mod.$provide('2Pi', function (Pi, callback) { callback(null, return 2*Pi); });
  // ...

array notation (minification-safe)

When your code is going to be minified or if you are about to make use of nested namespaces, the array notation is safer to use. All dependencies are listed as strings in the first part of the array, the last argument must be the actual module function.

  var mod = new Di();
  mod.$provide('Math.Pi',Math.PI, true);
  mod.$provide('2Pi', ['Math.Pi', function (Pi, callback) {
    callback(null, 2*Pi);
  }]);
  // ...

notation with "$inject" (minification-safe)

An alternative way is to provide a "$inject" property when using $annotate or $provide. This requires minification tools being in use not to mangle this key:


  class TestClass {
    constructor (pi) {
      this.RAD_TO_DEG = (180 / pi);
    }

    deg (value) {
      return value * this.RAD_TO_DEG;
    }
  }

  TestClass['$inject'] = ['PI'];

  var mod = new Di();
  mod.$provideValue('PI', Math.PI);
  mod.$resolve((err) => {
    if (err) { throw err; }
    let WrappedTestClass = mod.$annotate(TestClass);
    let instance = new WrappedTestClass();
    console.log(instance.deg(Math.PI * 2)); // 360
  });

Namespacing

Each dijs instance has a new namespace instance at its core. Namespaces provide getter/setter methods for sub-paths:

  var Namespace = require('dijs/lib/namespace');
  var namespace = new Namespace('home');
  namespace.floor = { chair : true };
  assert.deepEqual(namespace.$get('home.floor'), { chair : true})
  namespace.$set('home.floor.chairColor', 'blue');
  assert.deepEqual(namespace.floor, { chair: true, chairColor: 'blue' });

Please note that dijs assigns all namespace values to instances. You can disable this behavior using the "assign" option (see above).

Usage in the browser

Bundled versions are available in the dist/ folder.

You can create a minified build with Google's Closure compiler by running make in the project directory.

License

MIT (see LICENSE)