Skip to content

Instantly share code, notes, and snippets.

@trashhalo trashhalo/index.js
Created Aug 31, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.