• Stars
    star
    160
  • Rank 234,703 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Dependency injection for Express applications

express-di

Build Status Code Climate

Installation

npm install express-di

Compatibility

Express 3.x use express-di 3.x
Express 4.x use express-di 5.x or 4.x

Usage

To get started simply require('express-di') before var app = express(), and this module will monkey-patch Express, allowing you to define "dependencies" by providing the app.factory() method, after which you can use the "dependencies" in your routes following the Dependency Injection pattern(DI).

Example

In the past, if you want to pass variables between middlewares, you have to tack on properties to req, which seems odd and uncontrollable(that you couldn't point out easily which middleware add what properties to req). For example:

var express = require('express');
var app = express();

var middleware1 = function(req, res, next) {
  req.people1 = { name: "Bob" };
  next();
};

var middleware2 = function(req, res, next) {
  req.people2 = { name: "Jeff" };
  next();
};

app.get('/', middleware1, middleware2, function(req, res) {
  res.json({
    people1: req.people1,
    people2: req.people2
  });
});

require('http').createServer(app).listen(3008);

After using express-di, you can do this:

var express = require('express');
// Require express-di
require('express-di');
var app = express();

app.factory('people1', function(req, res, next) {
  next(null, { name: "Bob" });
});

app.factory('people2', function(req, res, next) {
  next(null, { name: "Jeff" });
});

app.get('/', function(people1, people2, res) {
  res.json({
    people1: people1,
    people2: people2
  });
});

require('http').createServer(app).listen(3008);

Define a dependency

The app.factory(name, fn) method is used to define a dependency.

Arguments

  • name: The name of the dependency.
  • fn: A function that is like a typical express middleware, takes 3 arguments, req, res and next, with a subtle difference that the next function takes 2 arguments: an error(can be null) and the value of the dependency.

Default dependencies

express-di has defined three default dependencies: req, res and next, so that you can use these arguments in your router middlewares just as before.

Cache

The same dependency will be cached per request. For instance:

app.factory('me', function(req, res, next) {
  // This code block will only be executed once per request.
  User.find(req.params.userId, next);
});

var checkPermission = function(me, next) {
  if (!me) {
    return next(new Error('No permission.'));
  }
  next();
};

app.get('/me', checkPermission, function(me, res) {
  res.json(me);
});

Where can I use DI?

You can use DI in your route-specific middlewares(aka app.get(), app.post(), app.put()...).

Sub App

Express-DI supports sub apps out of the box. Parent app cannot access the dependencies defined in the children apps, while children apps inherits the dependencies defined in the parent app:

var express = require('express');
require('express-di');
var mainApp = express();
var subApp = express();
mainApp.use(subApp);

mainApp.factory('parents', function(req, res, next) {
  next(null, 'parents');
});

subApp.factory('children', function(req, res, next) {
  next(null, 'children');
});

mainApp.get('/parents', function(children, res) {
  // throws error
  res.json(children);
});

subApp.get('/children', function(parents, res) {
  res.json(parents);
});

Performance

The process of DI will only be executed once at startup, so you don't need to worry about the performance.

You can test the performance using make bench.

Benchmark requires wrk to be installed first. You can run brew install wrk for Mac OS, or build it from sources for Ubuntu.

Test

  • make test
  • make test-cov will create the coverage.html showing the test-coverage of this module.

Articles and Recipes

License

The MIT License (MIT)

Copyright (c) 2014 Zihua Li

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

medis

💻 Medis is a beautiful, easy-to-use Mac database management application for Redis.
JavaScript
11,605
star
2

readability

📚 Turn any web page into a clean view
HTML
2,480
star
3

wechat-export

📃 Export WeChat chat histories to HTML files.
C
674
star
4

ranaly

📈 An easy to use chart system
JavaScript
498
star
5

CodeGame

🎮 JavaScript AI tank game
JavaScript
349
star
6

express-promise

❤️ Middleware for easy rendering of async Query results.
JavaScript
317
star
7

npm-try

🚆 Quickly try npm packages without writing boilerplate code.
TypeScript
113
star
8

bazinga

💥 The best all-in-one toolbox. Bazinga!
TypeScript
110
star
9

redis-book-assets

《Redis入门指南》第五章程序代码
JavaScript
92
star
10

serialize

Serialize an object including it's function into a JSON.
JavaScript
79
star
11

superfetch

A super powerful node.js HTTP client with the support of promise.
JavaScript
77
star
12

Hits-the-mole

The Hits-the-mole game implemented in pure CSS
CSS
62
star
13

colortype

A responsive WordPress theme
PHP
38
star
14

OhMyPullRequests

🚀 Access my pull requests from the menu bar
Swift
30
star
15

node_ranaly

Ranaly client library
JavaScript
19
star
16

express-mongoose

JavaScript
15
star
17

SwiftJSONFormatter

🪞 Formatter JSON delightfully.
Swift
15
star
18

teascript

Synchronous JavaScript
JavaScript
13
star
19

slicee

a CLI version of slicy.
Ruby
13
star
20

typo

妈妈从此再也不怕我输错属性(方法)名了!
JavaScript
12
star
21

dotQ

Yet another Q.
JavaScript
10
star
22

redis-book-v3-code

JavaScript
8
star
23

Tribbble

A Dribbble client for iPhone
Objective-C
7
star
24

blog

My blog
HTML
6
star
25

php-lugit-framework

简单优雅的PHP前端框架。
PHP
6
star
26

the-css-that-you-dont-know-about

你不知道的 CSS
HTML
6
star
27

quicker-npm-run

Alternative to `npm run` with support for autocomplete.
JavaScript
4
star
28

scene

A tiny front-end framework designed with ❤️
JavaScript
4
star
29

splitargs

Splitting Redis arguments as redis-cli
JavaScript
3
star
30

Suki

An elegant web framework for node.js
CoffeeScript
3
star
31

guokroup

将果壳所有小组的最新贴子显示在一页
CoffeeScript
3
star
32

cheerio-tester

Test the cheerio selector online
JavaScript
3
star
33

sample-NSSplitViewControlller

Swift
2
star
34

buddybook

books for buddies.
JavaScript
1
star
35

superspider

A powerful and distributed spider library used to crawl the web with the API of jQuery
1
star
36

3-key

⌨️ Personal key mapping for The Key.
C
1
star
37

SwiftPHPSerialization

Swift implementation of PHP's `serialize` and `unserialize`.
Swift
1
star
38

GameEngineSuki

A JavaScript Game Engine
CoffeeScript
1
star
39

express-sequelize

Adds Sequelize Promise support to Express rendering.
JavaScript
1
star
40

Threes-AI

A Threes! AI
CoffeeScript
1
star
41

dribbble

A full-featured Dribbble client for Node.js
JavaScript
1
star
42

my-first-ios-app

Swift
1
star
43

aqsort

An implementation of asynchronous quicksort in JavaScript
JavaScript
1
star