This is similar to this question, but my code has multiple routes.
The code works below for what I want to do, but I want to know if there's a cleaner way to write it as I'm fairly new to Node/Express/Redis.
var express = require('express');
var router = express.Router();
var io = require('socket.io');
var redis = require('./../lib/redis');
redis.get('count', function(err, value) {
if(err) throw err;
/* GET Dashboard */
router.get('/', function(req, res) {
res.render('dashboard', {title: 'Data Dashboard', count: value });
});
/* GET Backend */
router.get('/backend', function(req, res) {
res.render('backend', {title: 'Backend', count: value });
});
});
module.exports = router;
Basically, I'm just passing a single Redis key-value to both of my routes. Any suggestions to clean it up are appreciated.
The way your code is written you'll be passing the same value of the count key for your whole application life-cycle. There's nothing wrong with the code from a cleaning up perspective, but from a service point of view, the routes shouldn't be within the REDIS GET callback.
Getting the value within the route
// Use everytime you need to count the key
function redisCount = function(callback) {
redis.get('count', function(err, value) {
if(err) callback(err)
callback(null, value)
}
}
/* GET Dashboard */
router.get('/', function(req, res) {
redisCount(function(err,value) {
if(err) throw err;
res.render('dashboard', {title: 'Data Dashboard', count: value });
})
});
/* GET Backend */
router.get('/backend', function(req, res) {
redisCount(function(err,value) {
if(err) throw err;
res.render('backend', {title: 'Backend', count: value });
})
});
However if you do this count call for absolutely every single route, I would suggest a piece of middleware that just sets value into the context for every call:
Getting the value in a separate middleware
app.use(function (req, res, next) {
// using the same function for the redis count
redisCount(function(err, value) {
// respond with error
if (err) res.status("Could not connect to Redis")
// otherwise set the value in the session
req.session.value = value
// and move on to the next middleware
next()
});
});
// now simply declare your routes
/* GET Dashboard */
router.get('/', function(req, res) {
res.render('dashboard', {title: 'Data Dashboard', count: req.session.value });
});
/* GET Backend */
router.get('/backend', function(req, res) {
res.render('backend', {title: 'Backend', count: req.session.value });
});