Skip to content

Instantly share code, notes, and snippets.

@Darkbat91
Created December 4, 2019 15:57
Show Gist options
  • Save Darkbat91/d9b30b79ea64e1e27bc8540a4526f223 to your computer and use it in GitHub Desktop.
Save Darkbat91/d9b30b79ea64e1e27bc8540a4526f223 to your computer and use it in GitHub Desktop.
expressjs cache
// Cache layer for expressjs in typescript
// Based on https://medium.com/the-node-js-collection/simple-server-side-cache-for-express-js-with-node-js-45ff296ca0f0
// Caches the headers specifically to resolve CORS Errors i was running into with the implementation above.
var mcache = require('memory-cache');
let cache = (duration: number) => {
return (req: any, res: any, next: any) => {
let key = '__express__' + req.originalUrl || req.url
let headerkey = key + '-header'
let cachedBody = mcache.get(key)
let cachedheader = mcache.get(headerkey)
if (cachedBody) {
res.set(cachedheader)
res.send(cachedBody)
return
} else {
res.sendResponse = res.send
res.send = (body: any) => {
mcache.put(key, body, duration * 1000);
mcache.put(headerkey, res.headers, duration * 1000);
res.sendResponse(body)
}
next()
}
}
}
module.exports = function(app: any) {
var internal = require('../controllers/main');
app.route('/')
.get(cache(600))
.get(internal.query)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment