Created
August 8, 2017 13:32
-
-
Save mjurincic/05121677ec4f141c04fe334485d6da9d to your computer and use it in GitHub Desktop.
express caching
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 express = require('express'); | |
var app = express(); | |
var mcache = require('memory-cache'); | |
app.set('view engine', 'jade'); | |
var cache = (duration) => { | |
return (req, res, next) => { | |
let key = '__express__' + req.originalUrl || req.url | |
let cachedBody = mcache.get(key) | |
if (cachedBody) { | |
res.send(cachedBody) | |
return | |
} else { | |
res.sendResponse = res.send | |
res.send = (body) => { | |
mcache.put(key, body, duration * 1000); | |
res.sendResponse(body) | |
} | |
next() | |
} | |
} | |
} | |
app.get('/', cache(10), (req, res) => { | |
setTimeout(() => { | |
res.render('index', { title: 'Hey', message: 'Hello there', date: new Date()}) | |
}, 5000) //setTimeout was used to simulate a slow processing request | |
}) | |
app.get('/user/:id', cache(10), (req, res) => { | |
setTimeout(() => { | |
if (req.params.id == 1) { | |
res.json({ id: 1, name: "John"}) | |
} else if (req.params.id == 2) { | |
res.json({ id: 2, name: "Bob"}) | |
} else if (req.params.id == 3) { | |
res.json({ id: 3, name: "Stuart"}) | |
} | |
}, 3000) //setTimeout was used to simulate a slow processing request | |
}) | |
app.use((req, res) => { | |
res.status(404).send('') //not found | |
}) | |
app.listen(3000, function () { | |
console.log('Example app listening on port 3000!') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment