Skip to content

Instantly share code, notes, and snippets.

@markselby
Created October 28, 2013 02:19
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save markselby/7190454 to your computer and use it in GitHub Desktop.
Save markselby/7190454 to your computer and use it in GitHub Desktop.
Add Redis request caching to Node.js with Express.js.
var zlib = require('zlib');
var redis = require('redis');
var redisClient = redis.createClient();
var crypto = require('crypto');
// Our custom caching write function
function cached(body, lifetime, type) {
var key = this.req.originalUrl;
var res = this;
var etag, len;
if (typeof body === 'object') {
body = JSON.stringify(body);
}
zlib.gzip(body, function(err, result) {
if (err) return;
len = result.length;
etag = crypto.createHash('md5').update(result).digest('hex');
// Send the result to the client first
res.setHeader('ETag', etag);
res.setHeader('Cache-Control', 'max-age=' + lifetime);
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Content-Length', len);
res.setHeader('Content-Type', type);
res.end(result, 'binary');
// Add the result to the Redis cache
var hash = {
etag: etag,
max_age: lifetime,
content_type: type,
content_length: len,
content_encoding: 'gzip'
};
redisClient.hmset(key + '-meta', hash, redis.print);
redisClient.set(key + '-content', result, redis.print);
redisClient.expire(key + '-meta', lifetime);
redisClient.expire(key + '-content', lifetime);
});
};
// Now configure Express to know about the caching function
var express = require('express');
var response = express.response;
response.cached = cached;
// An example of using this for a request, 300 being the number of seconds that Redis will keep it for.
function someRoute(req, res) {
var content = "blah, blah, blah";
res.cached(content, 300, 'text/html');
}
@mhdatie
Copy link

mhdatie commented Oct 4, 2014

is this guaranteed? I'm trying to cache tweet results and the script looks neat and globally accessible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment