Reputation: 63
Hi I am using redis in a node.js app for user caching. After the user has been loged-in, the user information is cached, and accessed on every other request to determine what access the user has and the client receives information, views etc. based on that. Right now the app creates a redisClient at the beginning and passes that to the needed express route callbacks(which is pretty much all of them). To be honest I don't really like the extra argument that is being passed everywhere - especially when it is the same. Is there a better way to do it, and for instance if I a initialise the redisClient in every module will it have extra overhead
var express = require('express'),
loginFunctionality = require('./routes/login'),
homeFunctionality = require('./routes/home')
...
// Connect to redis
var redisClient = redis.createClient();
redisClient.on("error", function(err){
console.log("An error occurred with redis:" + err);
});
...
app.get('/', homeFunctionality.home);
app.post('/register', loginFunctionality.createNewUser);
app.post('/login', loginFunctionality.login(redisClient, secret));
...
what I am wondering is, if there is a good way to remove the redisClient parameter.
Upvotes: 3
Views: 2234
Reputation: 203534
You can pass the client along with every request through a middleware:
// initialization
var client = redis.createClient(...);
app.use(function(req, res, next) {
req.redis = client;
next();
});
// a route handler
app.get('/', function(req, res) {
req.redis.get(...);
...
});
Or, if applicable, you could create a more elaborate middleware that would perform the cache lookups itself and pass the user data along with the request, so you don't have to perform the lookup in each request handler.
Or you could move the Redis client initialization to a separate module and require that from each of the files you need it:
// redis-client.js
var redis = require('redis');
module.exports = redis.createClient(...);
// elsewhere
var client = require('./redis-client');
app.get('/', function(req, res) {
client.get(...);
...
});
added on JAN 16th, 2019
Remember that with this technique, you can easily shut down the connection if something (like Ctrl+C) disconnects your server, simply by adding the client.quit()
.
process.on('SIGTERM', () => {
if (client) {
console.log('Ending CACHE connection');
client.quit();
}
console.log('Closing server...');
app.close(() => {
console.log('server was closed!');
process.exit(0);
});
});
Upvotes: 12