最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding custom properties to Express app and req. What's the best way? - Stack Overflow

programmeradmin6浏览0评论

Am I shooting myself in the foot:

I want to make config, core, and mean available on the app and req objects in my Express app.

I'm using properties not in the 4.x API. Anything I should know?

Is there a problem with just adding them as properties?

// express.js
module.exports = function(db, config, meanModules) {

  var app = express();

  // ... 

  // Get mean-core
  var core = require('meanjs-core')(db, config);

  // Attach config, core, and modules to app    <==== POSSIBLE FOOT SHOOTING
  app.config = config;
  app.core = core;
  app.mean = meanModules;

  // Middleware to adjust req
  app.use(function(req, res, next) {
    // Add config, core, and modules to all requests  <==== POSSIBLE FOOT SHOOTING
    req.config = config;
    req.core = core;
    req.mean = meanModules;
    next();
  });

  // ...
}

Am I shooting myself in the foot:

I want to make config, core, and mean available on the app and req objects in my Express app.

I'm using properties not in the 4.x API. Anything I should know?

Is there a problem with just adding them as properties?

// express.js
module.exports = function(db, config, meanModules) {

  var app = express();

  // ... 

  // Get mean-core
  var core = require('meanjs-core')(db, config);

  // Attach config, core, and modules to app    <==== POSSIBLE FOOT SHOOTING
  app.config = config;
  app.core = core;
  app.mean = meanModules;

  // Middleware to adjust req
  app.use(function(req, res, next) {
    // Add config, core, and modules to all requests  <==== POSSIBLE FOOT SHOOTING
    req.config = config;
    req.core = core;
    req.mean = meanModules;
    next();
  });

  // ...
}
Share Improve this question asked May 17, 2014 at 22:50 Michael ColeMichael Cole 16.3k7 gold badges89 silver badges98 bronze badges 2
  • Why do you need to do this in the first place? – mscdex Commented May 17, 2014 at 22:54
  • I want to patch controllers and services from other npm packages onto my app. meanjs-core would have controllers from outside my application. These could be updated via npm. e.g. app.route('/auth/confirm/:confirmationCode').get(app.core.users.checkEmailVerification); – Michael Cole Commented May 18, 2014 at 3:37
Add a ment  | 

1 Answer 1

Reset to default 7

I would remend attaching a single property to app that's probably never going to conflict, and accessing everything from there, like app.myLibrary.

app.myLibrary = {config: config, core: core, mean: meanModules};

And access app.myLibrary from within routes/middleware:

req.app.myLibrary

Unless something dynamic is happening in the middleware that varies per request, it's likely better to just access it with req.app.myLibrary.

发布评论

评论列表(0)

  1. 暂无评论