Skip to content
Myr

app.js

This file

Path

examples/cache/app.js

95 lines · 2.2 KiB · JavaScript

Last changed by

Added strategic cache example (with redis)Tj Holowaychukbefore adoptiona90fd85

History of this file

Take it

Added strategic cache example (with redis)Tj Holowaychukbefore adoptiona90fd85

lines 1–95why, one step back
1
2// Expose modules in ./support for demo purposes3require.paths.unshift(__dirname + '/../../support');45/**6 * Module dependencies.7 */89var express = require('./../../lib/express')10 , redis = require('redis')11 , _cache = redis.createClient()12 , app = express.createServer();1314// $ npm install redis15// if you do not have the redis client installed16// and start redis via $ redis-server1718app.set('views', __dirname + '/views');19app.set('view engine', 'ejs');2021// Generate 50 random users for display22var n = 50;23var users = [];24while (n--) {25 users.push({ name: 'user ' + n, email: n + '@vision-media.ca' });26}2728// example cache middleware. we proxy writeHead etc to29// cache the response, and we could perform additional30// checks on headers etc to extend our caching logic.31//32// Please note in this example you would have to33// handle write() encodings as well, this is just an example :)3435function cache(req, res, next){36 _cache.get(req.url, function(err, data){37 try {38 if (data) {39 data = JSON.parse(data.toString());40 delete data.headers['X-Response-Time'];41 res.writeHead(data.status, data.headers);42 res.end(data.body);43 } else {44 proxyCache(req, res);45 next();46 }47 } catch (err) {48 // Ignore49 next();50 }51 });52}5354function proxyCache(req, res){55 var writeHead = res.writeHead56 , write = res.write57 , end = res.end58 , ok = false59 , cache = { body: '' };6061 // Proxy writeHead62 res.writeHead = function(status, headers){63 res.writeHead = writeHead;64 res.writeHead(status, headers);65 if (status >= 300) return ok = false;66 cache.status = status;67 cache.headers = headers;68 };6970 // Proxy write71 res.write = function(data){72 res.write = write;73 cache.body += data;74 res.write(data);75 };76 77 // Proxy write78 res.end = function(data){79 res.end = end;80 cache.body += data;81 res.end(data);82 83 // Serialize / cache data84 _cache.set(req.url, JSON.stringify(cache));85 };86}8788// Apply to any route(s) as route-specific middleware8990app.get('/', cache, function(req, res){91 res.render('users', { users: users });92});9394app.listen(3000);95console.log('Express app started on port 3000');