Skip to content

Instantly share code, notes, and snippets.

@trashhalo
Created August 31, 2017 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trashhalo/080fdfec97428ef70620ed14cbd65dfd to your computer and use it in GitHub Desktop.
Save trashhalo/080fdfec97428ef70620ed14cbd65dfd to your computer and use it in GitHub Desktop.
node cache proxy
'use strict';
require('perish');
var Redis = require('ioredis');
var redis = new Redis();
const http = require('http');
const httpProxy = require('http-proxy');
const streamToPromise = require('stream-to-promise');
const proxy = httpProxy.createProxyServer({
changeOrigin: true
});
const key = (req) => req.url;
proxy.on('proxyRes', (proxyRes, req) => {
streamToPromise(proxyRes).then((data) => {
const metadata = {
headers: proxyRes.headers,
statusCode: proxyRes.statusCode
};
const reqKey = key(req);
redis
.multi()
.set(reqKey, JSON.stringify(metadata))
.set(reqKey, data)
.exec();
});
});
const server = http.createServer((req, res) => {
const reqKey = key(req);
redis
.pipeline()
.get(reqKey)
.getBuffer(`${reqKey}.data`)
.exec()
.then(([[, metadataStr], [, cache]]) => {
if (cache === null) {
proxy.web(req, res, {
target: 'http://echo.jpillora.com/'
});
} else {
const metadata = JSON.parse(metadataStr);
Object.assign(res.headers, metadata.headers);
res.statusCode = metadata.statusCode;
res.write(cache);
res.end();
}
});
});
server.listen(8080, () => {
console.log('Example app listening on port 8080!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment