Created
August 31, 2017 12:28
-
-
Save trashhalo/080fdfec97428ef70620ed14cbd65dfd to your computer and use it in GitHub Desktop.
node cache proxy
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'; | |
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