Bobby Shark
Bobby Shark

Reputation: 1074

Nodejs + Express4 : Export variable from module and access it in route

I want to make a module that retrieves some infos from the database. Since I need the code in most of my routes I thought a module would perfectly fit for it.

So basicaly my module query the database and push results into an array. The problem is I can't access the array in my route page.

Is it possible or should I store the array into session or some res.local variable, or am I doing something wrong with the module.exports function ?

Here is a part of the module code :

function myModule(req, res, next){
    if(req.session.userid){
        var result = [];
        //query the db etc...
        return result;      
    }else{
        return next();
    }               
}

module.exports = myModule;

And my route :

var myModule= require('./middleware/mymodule');

module.exports = function(app){
   app.get('something', function(req, res){
       console.log(myModule);
   });
};

The console.log(myModule) returns [Function: myModule].

Also what is the difference of using app.get('something', myModule, function(req, res){, is it only to send a custom response ?

Thanks for your help

Upvotes: 0

Views: 102

Answers (1)

Jordonias
Jordonias

Reputation: 5848

You are trying to use middleware wrong. One approach you could do is create middleware that adds the result to your request object.

myMiddleware.js

function myMiddleware(req, res, next) {
  var result = [];
  if(req.session.userid) {
    //query the db etc
  }
  req.myResult = result;  // May be empty if no req.session.userid
  return next();
}
module.exports = myMiddleware;

route.js

var myMiddleware = require('./middleware/myMiddleware');

module.exports = function(app) {
  app.get('something', myMiddleware /* Use myMiddleware */, function(req, res) {
    console.log(req.myResult);  // The result is part of the request object
    return res.send('Hello world');
  }
}

When you use:

app.get('something', myMiddleware, function(req, res) {

You are saying first call myMiddleware, and then next(); is calling your route function, while passing the changed req object and res object.

Upvotes: 1

Related Questions