2

I would like to pass additional data from app.js to express-resource routes and I have not figured out yet. How would you do that? Note that I'm using express-resource

// app.js
var myAddOnData = 'abc';
app.resource('users', './routes/user');

// user.js
exports.index = function (req, res) {
   console.log(myAddOnData);
};

Thanks

Nam Nguyen
  • 5,668
  • 14
  • 56
  • 70
  • I saw people use init function but I'm not sure express-resource will have a better solution? http://stackoverflow.com/questions/12030521/pass-variable-to-expresjs-3-routes?lq=1 – Nam Nguyen Aug 31 '13 at 00:02

1 Answers1

1

These are the three approaches I can think of. Without the little I know about your specific problem, it sounds like middleware might be the way to do it.

With a global app variable

Create a value using app.set in app.js and then retrieve it using app.get in user.js.

Using a module

Store the information in an isolated module, then require() as needed. If this is running across multiple instances, you'd obviously want to store the values to disk as opposed to in memory.

// keystore.js
// -----------
module.exports.set = function(id, val) { /* ... */ };
module.exports.get = function(id) { /* ... */ };


// app.js
// -----------
var ks = require('./keystore');
ks.set = function("userInfo", "abc");
module.exports.get = function(id) { /* ... */ };


// user.js
// -----------
var ks = require('./keystore');
ks.get = function("userInfo", "abc");

(Maybe check out pot?)

Using Middleware

Use custom middleware to attach data to the request object which can then be accessed later in the route handlers.

//app.js
//------
var express = require('express')
  , cookieSessions = require('./cookie-sessions');

var app = express();

app.use(express.cookieParser('manny is cool'));
app.use(cookieSessions('sid'));
// ...

//cookie-sessions.js
//------------------
module.exports = function(name) {
  return function(req, res, next) {
    req.session = req.signedCookies[name] || {};

    res.on('header', function(){
      res.signedCookie(name, req.session, { signed: true });
    });

    next();
  }
}

via https://gist.github.com/visionmedia/1491756

Jesse Fulton
  • 2,188
  • 1
  • 23
  • 28
  • this will require app to be global and I'm not sure this is the best practice. I'm running my app using cluster for multi processes, using global will screw me up badly. – Nam Nguyen Sep 01 '13 at 05:47
  • Almost every express example I have seen uses a global `app` var, but you could just as easily wrap your main application (`app`) using the module pattern and the `get`/`set` approach should still work then. Or you could probably also get away with a straight key/value store module. If that's not your style, you could try writing some custom middleware to inject the values. – Jesse Fulton Sep 01 '13 at 09:44