Created
October 28, 2013 02:19
-
-
Save markselby/7190454 to your computer and use it in GitHub Desktop.
Add Redis request caching to Node.js with Express.js.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is this guaranteed? I'm trying to cache tweet results and the script looks neat and globally accessible.