Last active
December 30, 2015 04:49
-
-
Save craigspaeth/7778476 to your computer and use it in GitHub Desktop.
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
| # | |
| # Barebones HTML caching with Redis | |
| # | |
| redis = require("redis") | |
| client = redis.createClient() | |
| app.get '/', (req, res, next) -> | |
| # Check if the request is cached | |
| client.get req.url, (err, cachedHtml) -> | |
| return next(err) if err | |
| return res.send(cachedHtml) if cachedHtml | |
| # Typical page rendering code | |
| fetchSomeThings (someThings) -> | |
| res.render 'index', { someThings: someThings }, (err, html) -> | |
| # Set the cache | |
| client.set(req.url, html) | |
| # | |
| # DRYed up with a helper | |
| # | |
| # lib/cache_helpers.coffee | |
| redis = require("redis") | |
| client = redis.createClient() | |
| @renderCached = (req, res, next) -> | |
| client.get req.url, (err, html) -> | |
| return next(err) | |
| return res.send(html) if html | |
| next() | |
| @cache = (err, html) -> | |
| client.set(req.url, html) | |
| # routes file | |
| { renderCached, cache } = require '../../lib/cacheHelpers' | |
| app.get '/', renderCached, (req, res, next) -> | |
| fetchSomeThings (someThings) -> | |
| res.render 'index', { someThings: someThings }, cache | |
| # | |
| # Example in artwork routes | |
| # | |
| @mainPage = (req, res, next) -> | |
| # Check if the request is cached and render the cached html instead | |
| client.get req.url, (err, cachedHtml) -> | |
| return next(err) if err | |
| return res.send(cachedHtml) if cachedHtml | |
| # Otherwise go on with the normal fetch code | |
| artwork = new Artwork(id: req.params.id) | |
| artwork.fetch | |
| success: -> | |
| res.locals.sd.ARTWORK = artwork.toJSON() | |
| res.render 'main_page', artwork: artwork, (err, html) -> | |
| # Successful fetch, store the HTML in Redis and set a timeout to invalidate | |
| client.set(req.url, html) | |
| setTimeout (-> client.del(req.url)), 60 * 60 * 1000 | |
| error: res.backboneError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment