All Projects → opentable → spur-ioc

opentable / spur-ioc

Licence: MIT license
Dependency Injection library for Node.js

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to spur-ioc

Ts ci
✅ Continuous integration setup for TypeScript projects via GitHub Actions.
Stars: ✭ 225 (+765.38%)
Mutual labels:  npm-package
Terminal Image Cli
Display images in the terminal
Stars: ✭ 234 (+800%)
Mutual labels:  npm-package
Oclazyload
Lazy load modules & components in AngularJS
Stars: ✭ 2,661 (+10134.62%)
Mutual labels:  npm-package
Json2typescript
Convert JSON to TypeScript with secure type checking!
Stars: ✭ 230 (+784.62%)
Mutual labels:  npm-package
Nodehun
The Hunspell binding for NodeJS that exposes as much of Hunspell as possible and also adds new features. Hunspell is a first class spellcheck library used by Google, Apple, and Mozilla.
Stars: ✭ 229 (+780.77%)
Mutual labels:  npm-package
Typescript Lib Starter
Typescript library starter
Stars: ✭ 235 (+803.85%)
Mutual labels:  npm-package
Bitcoin Chart Cli
Bitcoin chart for the terminal as command line util
Stars: ✭ 221 (+750%)
Mutual labels:  npm-package
themer.js
🌗 Automatically switch between dark and light themes at sunset and sunrise using the user's location.
Stars: ✭ 28 (+7.69%)
Mutual labels:  npm-package
Stimulus Components
A modern Stimulus library delivering common JavaScript behaviors with a bunch of customizable controllers.
Stars: ✭ 234 (+800%)
Mutual labels:  npm-package
Wait For Localhost
Wait for localhost to be ready
Stars: ✭ 245 (+842.31%)
Mutual labels:  npm-package
Node Virtualbox
A JavaScript Library for Interacting with VirtualBox
Stars: ✭ 231 (+788.46%)
Mutual labels:  npm-package
Pupa
Simple micro templating
Stars: ✭ 231 (+788.46%)
Mutual labels:  npm-package
Node S3 Uploader
Flexible and efficient resize, rename, and upload images to Amazon S3 disk storage. Uses the official AWS Node SDK for transfer, and ImageMagick for image processing. Support for multiple image versions targets.
Stars: ✭ 237 (+811.54%)
Mutual labels:  npm-package
React Npm Boilerplate
Boilerplate for creating React Npm packages with ES2015
Stars: ✭ 226 (+769.23%)
Mutual labels:  npm-package
Singlespotify
🎵 Create Spotify playlists based on one artist through the command line
Stars: ✭ 254 (+876.92%)
Mutual labels:  npm-package
Eslint Plugin Eslint Comments
Additional ESLint rules for directive comments of ESLint.
Stars: ✭ 221 (+750%)
Mutual labels:  npm-package
Cycled
Cycle through the items of an array
Stars: ✭ 235 (+803.85%)
Mutual labels:  npm-package
quetie
🎀 Just the cutest and tiniest queue/deque implementation!
Stars: ✭ 111 (+326.92%)
Mutual labels:  npm-package
js-stack-from-scratch
🌺 Russian translation of "JavaScript Stack from Scratch" from the React-Theming developers https://github.com/sm-react/react-theming
Stars: ✭ 394 (+1415.38%)
Mutual labels:  npm-package
Unsplash Wallpaper
Use an image from unsplash.com as your background image from a simple command.
Stars: ✭ 238 (+815.38%)
Mutual labels:  npm-package

Spur: IoC

Dependency Injection library for Node.js.

NPM Version NPM Install Size NPM Downloads

About the Spur Framework

The Spur Framework is a collection of commonly used Node.JS libraries used to create common application types with shared libraries.

Visit NPMJS.org for a full list of Spur Framework libraries >>

Topics

Features

  • Dependency injection (IoC) inspired by AngularJS
  • Auto injects folders
  • Ability to merge injectors
  • Ability to link injectors
  • Makes testing super easy
    • Ability to substitute dependencies in tests
  • Resolution of dependencies by querying via regular expression
  • Clear error stack trace reporting
  • Supports active Node versions in the LTS Schedule. (view current versions)

What is inversion of control and why you should use it?

Inversion of Control (IoC) is also known as Dependency Injection (DI). IoC is a pattern in which objects define their external dependencies through constructor arguments or the use of a container factory. In short, the dependency is pushed to the class from the outside. All that means is that you shouldn't instantiate dependencies from inside the class.

Inversion of control is used to increase modularity of the program and make it extensible, and has applications in object-oriented programming and other programming paradigms.

It allows for the creation of cleaner and more modular code that is easier to develop, test and maintain:

  • Single responsibility classes
  • Easier mocking of objects for test fixtures
  • Easier debugging in Node.js' async environment

Quick start

Installation

$ npm install spur-ioc --save

Usage

Here is a quick example that sets up the definition of an injector, some dependencies and a startup script.

src/injector.js

const spur = require('spur-ioc');

module.exports = function(){
  // define a  new injector
  const ioc = spur.create('demo');


  //register external dependencies or globals
  ioc.registerDependencies({
    '_'           : require('underscore'),
    'path'        : require('path'),
    'console'     : console,
    'nodeProcess' : process
  });

  // register folders in your project to be auto-injected
  ioc.registerFolders(__dirname, [
    'demo'
  ]);

  return ioc;
}

src/demo/Tasks.js

Example of file that depends on an injectable dependency. This example shows the usage of underscore (_).

module.exports = function(_){
    return _.map([1,2,3], function(num) {
        return 'Task ' + num;
    });
}

src/demo/TasksPrinter.js

This example injects Tasks and console dependencies, both previously defined in the injector.

module.exports = function(Tasks, console){
    return {
        print: function(){
          console.log(Tasks);
        }
    };
}

src/start.js (top declaration file)

Example of how to create an instance of the injector and start the app by using one of its dependencies.

const injector = require('./injector');

injector().inject(function(TasksPrinter){
  TasksPrinter.print();
});
Usage note for ES6 syntax

While it is tempting to utilize the fat arrow syntax in this top declaration file like the example below, it will not be supported by spur-ioc. For more information, read issue #26. Instead use the recommended approach above. There isn't a compelling reason to add that additional support. If you use this style, it will break as the report in issue #26.

const injector = require('./injector');

injector().inject((TasksPrinter) => {
  TasksPrinter.print();
});

Writing tests

Dependency injection really improves the ease of testing, removes reliance on global constiables and allows you to intercept seams and make dependencies friendly.

test/unit/TasksPrinterSpec.js

const injector = require('../../src/Injector');

describe('TasksPrinter', () => {
  beforeEach(function () {
    this.mockConsole = {
      logs:[],
      log: () => this.logs.push(arguments)
    };

    // below we replace the console dependency silently
    injector()
      .addDependency('console', this.mockConsole, true)
      .inject((TasksPrinter) => {
        this.TasksPrinter = TasksPrinter;
      });
  });

  it('should exist', function () {
    expect(this.TasksPrinter).to.exist;
  });

  it('should greet correctly', function () {
    this.TasksPrinter.print();
    expect(this.mockConsole.logs[0][0]).to.deep.equal([
        'Task 1', 'Task 2', 'Task 3'
    ]);
  });
});

Error reporting

One of the great things about ioc is that you get real application dependency errors upfront at the start of your application.

Missing dependency with typo

module.exports = function (TaskZ, console) {
  //...
}

// Produces:
// ERROR Missing Dependency TaskZ in  $$demo -> TasksPrinter -> TaskZ

Adding a cyclic dependency back to TasksPrinter in Tasks.js

module.exports = function (_, TasksPrinter) {
  //...
}

// Produces:
// ERROR Cyclic Dependency TasksPrinter in  $$demo -> TasksPrinter -> Tasks -> TasksPrinter

Contributing

We accept pull requests

Please send in pull requests and they will be reviewed in a timely manner. Please review this generic guide to submitting a good pull requests. The only things we ask in addition are the following:

  • Please submit small pull requests
  • Provide a good description of the changes
  • Code changes must include tests
  • Be nice to each other in comments. 😇

Style guide

The majority of the settings are controlled using an EditorConfig configuration file. To use it please download a plugin for your editor of choice.

Lint source code by running npm run lint.

All tests should pass

To run the test suite, first install the dependancies, then run npm test

$ npm install
$ npm test

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].