Created
January 18, 2020 04:25
-
-
Save mrm8488/84dc49434ef53c52851e81d9ade349bf to your computer and use it in GitHub Desktop.
Simple Express cache
This file contains 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