Skip to content

Instantly share code, notes, and snippets.

@rodolfo42
Last active April 24, 2017 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodolfo42/6614e398fca727d4dea05128cc8c79bb to your computer and use it in GitHub Desktop.
Save rodolfo42/6614e398fca727d4dea05128cc8c79bb to your computer and use it in GitHub Desktop.
Example of dependency injection with modules

@team/corelib library

lib/stats.js

This is a stats lib that has no dependencies but needs to be initialized.

module.exports = function initializeStats(projectName, options) {
  return {
    isInitialized: true,
    options,
    metric: function metric(args) {
      // code using projectName, options
    }
  };
}

lib/instrument.js

This is a lib module that needs an already-initialized stats module to work.

module.exports = function instrument(stats) {
  // fail early
  if (!stats.isInitialized) {
    throw new Error('stats not initialized. see <link>');
  }

  // immutable operation that returns a brand new module instance
  return {
    instrumentedFetch: function instrumentedFetch(args) {
      // code using initialized stats module
    }
  };
};

In the client project

lib/stats.js

const stats = require('@team/corelib/lib/stats');

// some project-wide options
const projectName = 'project-name';
const projectOptions = {};

// immutable operation in the stats module
module.exports = stats(projectName, projectOptions);

lib/instrument.js

const instrument = require('@team/corelib/instrument');
const stats = require('./stats'); // already initialized stats

// immutable operation in the instrument module
module.exports = instrument(stats);

foobar.js

const { instrumentedFetch } = require('./lib/instrument');

// already configured with an initialized stats but not need to pass it along to every call
instrumentedFetch(args);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment