Giter Club home page Giter Club logo

express-di's Introduction

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.

express-di's People

Contributors

bitdeli-chef avatar floatdrop avatar jarvisaoieong avatar luin avatar luki- avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-di's Issues

koa compatibility?

Any chance to use this with koa? Looks great. Simple and straight to the point.

Dependent dependencies

Hi! Thank you for awesome tool for structuring middlewares. I like the way, how dependencies is resolved by argument name, but there is a some kind of missed feature, that would bump usage cases of express-di to the space.

Suppose I want to declare dependent factory people2 on already defined people1 and use it in people2 code:

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(people1, req, res, next) {
    next(null, { people1: people1, name: "Jeff" });
});

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

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

What I expect to see is:

{
    "people2": {
        "people1": { "name": "Bob" },
        "name": "Jeff"
    }
}

But what I get is undefined is not a function from next(...) call:

TypeError: undefined is not a function
    at app.get.res.json.people2 (/Users/floatdrop/express-di-test/index.js:11:5)
    at /Users/floatdrop/node_modules/express-di/lib/di.js:65:13
    at /Users/floatdrop/node_modules/express-di/node_modules/async/lib/async.js:227:13
    at iterate (/Users/floatdrop/node_modules/express-di/node_modules/async/lib/async.js:134:13)
    at async.eachSeries (/Users/floatdrop/node_modules/express-di/node_modules/async/lib/async.js:150:9)
    at _asyncMap (/Users/floatdrop/node_modules/express-di/node_modules/async/lib/async.js:226:9)
    at /Users/floatdrop/node_modules/express-di/node_modules/async/lib/async.js:216:23
    at /Users/floatdrop/node_modules/express-di/lib/di.js:37:9
    at callbacks (/Users/floatdrop/node_modules/express/lib/router/index.js:164:37)
    at param (/Users/floatdrop/node_modules/express/lib/router/index.js:138:11)

I suppose resolving in factory method is just not implemented yet, if so - do you have plans for it?

Not work with 'composable-middleware' module

Express-di doesn't work with composable-middleware. I use it to group verify authenticate and express-di show this error when i call to create route 'Unrecognized dependency: out' express-di.
out is function under 'composable-middleware' module.

// auth.isAuthenticated() ->> call composable middleware with 2 
router.post('/', auth.isAuthenticated(), controller.create);
// my authen
export function isAuthenticated() {
  return compose()
  // Validate jwt
    .use(function (req, res, next) {
      // allow access_token to be passed through query parameter as well
      if (req.query && req.query.hasOwnProperty('access_token')) {
        req.headers.authorization = 'Bearer ' + req.query.access_token;
      }
      validateJwt(req, res, next);
    })
    // Attach user to request
    .use(function (req, res, next) {
      User.findById(req.user._id).exec()
        .then(user => {
          if (!user) {
            return res.status(401).end();
          }
          req.user = user;
          next();
        })
        .catch(err => next(err));
    });
}
// error line code in express-id with dependency is 'out' value
if (!factory) {
        throw new Error('Unrecognized dependency: ' + dependency);
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.