Komo
Komo

Reputation: 2138

Express.js : calling internal services

I'm kind of new regarding node.js, express.js and REST APIs.

Here is my issue :

I need to load user info from my database (mongoDB if that is relevant) in multiple cases.

What is the best practice in this case ?

1) Loading directly from the database :

index.js :

db.collection('usercollection').findOne({email:  req.user.email}, function(err, result){...

2) Calling a service from another route which reads from the database :

users.js :

/* GET user by email */
router.get('/:email', function(req, res) {

    var db = req.db;
    var email = req.params.email;
    db.collection('usercollection').findOne({email:  email}, function(err, result) {
    if (err) throw err;
    res.json(result);
    });

});

index.js :

//Call users/email/emailParameterURL

3) None of these two ?

Thanks for your time

Upvotes: 1

Views: 5296

Answers (2)

Luke H
Luke H

Reputation: 3163

Personally I try to keep my application logic as separate from the Express routes as possible.

So, I create my own controller modules (or call them what you will), which receive database and configuration variables (allows for swapping out later if required, or mocking for testing).

In the routes, I use these controller classes, passing them the database.

This allows me to rapidly and cleanly unit test my core logic, without having to deal with express. Otherwise, one ends up only able to do integration testing on the routes.

It also allows you to change your routes around easily later without breaking your application.

Also, I can't recommend Bluebird promises enough. These allow me to greatly simplify things, and avoid a lot of callback hell.

A tiny example:

/// usercontroller.js
var UserController = {
   _database: null,
   setDatabase: function(db) { this._database = db; },

   findUserByEmail: function(email, callback) {
       this._database.collection('usercollection').findOne({email:  req.user.email}, callback);
   }
};

module.exports = UserController;

/// routes.js

/* GET user by email */
router.get('/:email', function(req, res) {
    var UserController = require('./usercontroller');
    var db = req.db;
    UserController.setDB(db);
    UserController.findUserByEmail(req.params.email, function(err, result) {
        if (err) throw err;
        res.json(result);
    });
});

Upvotes: 3

PashaB
PashaB

Reputation: 109

lets say if want an authorised access to your api you can not do anything in first case. If you don't security enhanced access first case can work, but if you want more control over your api use second one. By control I mean manipulation with data, maybe you have some hashed values and so on...

Upvotes: 0

Related Questions