2

I need to inject my db object into the securityHandler object, but I can't seem to work out how to do it.

In the securityHandler.authenticate method I want to have access to all: db, request and response.

I've tried this:

app.post('/api/login', securityHandler.authenticate(request, response, db) );

and

SecurityHandler.prototype.authenticate = function authenticate(request, response, db) {};

EDIT:

nane suggested passing the db object to the constructor of SecurityHandler:

var security = new SecurityHandler(db);

SecurityHandler itself looks like this:

function SecurityHandler(db) {
    console.log(db); // Defined
    this.db = db;
}

SecurityHandler.prototype.authenticate = function authenticate(request, response, next) {
    console.log(this.db); // Undefined
};

The db object now exists in the constructor method, but for some reason is unaccessible in the authenticate method.

Markus Pint
  • 348
  • 3
  • 17
  • `securityHandler` is an object that was create using `securityHandler = new SecurityHandler()`? And what is `db` (where is this defined/created) it nothing standard in express routing. – t.niese Feb 15 '15 at 16:08
  • Both were created by me, yes with the "new" keyword. – Markus Pint Feb 15 '15 at 16:10
  • 1
    why not inject into the the `SecurityHandler` constructor `securityHandler = new SecurityHandler(db)`, or just require there ... – eenagy Feb 15 '15 at 16:16
  • 2
    try this http://stackoverflow.com/questions/9250851/do-i-need-dependency-injection-in-nodejs-or-how-to-deal-with – eenagy Feb 15 '15 at 16:31

2 Answers2

0

securityHandler.authenticate(request, response, db) would immediately call authenticate as of that you would pass the result of the authenticate call as callback to app.post('/api/login', /*...*/).

You would need to do it that way:

app.post('/api/login', function(request, response) {
   securityHandler.authenticate(request, response, db);
});
Craig
  • 6,869
  • 3
  • 32
  • 52
t.niese
  • 39,256
  • 9
  • 74
  • 101
0

You can write a custom middleware in express.js and use it before route any request.

For more about custom middleware - you can refer - Express.js Middleware Demystified

Now in this middleware you can implement authentication related functionality which will fire before all request and you can manipulate code on basis of your request.url in the middleware itself.

Hope this will help you. Thanks.

Piyas De
  • 1,786
  • 15
  • 27