Answer the question
In order to leave comments, you need to log in
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>
})
Answer the question
In order to leave comments, you need to log in
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();
})
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.
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 questionAsk a Question
731 491 924 answers to any question