Created
September 4, 2017 22:18
-
-
Save metainfa/8ef5ee8940b352507f10b5548a8d7d12 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
'use strict' | |
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(process.env.PORT, function () { | |
console.log(`Example app listening on port ${process.env.PORT}!`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment