Skip to content

Instantly share code, notes, and snippets.

@meowgorithm
Forked from markselby/node-express-redis-cache.js
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meowgorithm/9182771 to your computer and use it in GitHub Desktop.
Save meowgorithm/9182771 to your computer and use it in GitHub Desktop.
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