K
K
Konstantin Kitmanov2013-02-04 13:11:06
Express.js
Konstantin Kitmanov, 2013-02-04 13:11:06

Expressjs app and global data?

How correct is it to store global data in middleware?

I have a small expressjs application. There is some data that is displayed on all pages and it is reluctant to pull it from the database every time (an extra request, an extra asynchronous call in the code). It is quite possible to read them from a DB time in half an hour. Therefore, I wrote a middleware that goes to the database on schedule, and with each request puts the available data into the req object:

app.use(function (req, res, next) { <br>
    req.cities = myMiddleware.cities; <br>
    next();<br>
})


In general, everything works as I expected, but there are vague doubts about the "orthodoxy" of this approach.
Who implemented such things?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
pomeo, 2013-02-04
@k12th

they have it and it is recommended to do it
github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x
(use middleware + res.locals)
example

  app.use(require('connect-flash')());
  // Expose the flash function to the view layer
  app.use(function(req, res, next) {
    res.locals.flash = function() { return req.flash() };
    next();
  })

V
Vyacheslav Slinko, 2013-02-04
@KeepYourMind

Yes, everything is fine, but I would not implement it in req and make a function for the request.
If the application is generally single-page, then I would simply use a variable.

K
Keenest, 2013-02-04
@Keenest

I did this:

var cacheDB; // обновляется из БД раз в полчаса (либо при событии-изменении данных) 

mw = function (req, res, next) { // прослойка, добавляющая кэш БД к реквесту
    req.session.dataDB = cacheDB;
    next();
};

app.get('/', mw, function (req, res) { // добавляем mw сюда
    // рендерим страницу / обрабатываем данные в зависимости от реквеста
});

// и так далее
app.get('/about', mw, function (req, res) {
    // ..
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question