-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreqcache.js
75 lines (56 loc) · 1.88 KB
/
reqcache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const axios = require('axios').default;
const Koa = require('koa');
const koaBody = require('koa-body');
const unparsed = require('koa-body/unparsed');
if (process.argv.length < 4) {
console.log(`Usage: node reqcache port http://example.com/base/url`);
process.exit(1);
}
const config = {
port: process.argv[2],
proxyBase: process.argv[3],
debug: process.argv[4] === 'debug',
};
let cache = new Map();
const app = new Koa();
app.use(koaBody({includeUnparsed: true}));
app.use(async ctx => {
let method = ctx.request.method;
let fullUrl = ctx.request.url;
let body = ctx.request.body[unparsed];
let headers = ctx.request.headers;
delete headers.host;
let key = makeMapKey({method, fullUrl, body, headers});
if (!cache.has(key)) {
cache.set(key, await makeRequest({method, fullUrl, body, headers}));
}
if (config.debug) console.debug(`get from cache: ${method} ${fullUrl}`);
let resp = cache.get(key);
ctx.response.status = resp.status;
for (let hdr in resp.headers) {
ctx.set(hdr, resp.headers[hdr]);
}
ctx.response.body = resp.body;
});
app.listen(config.port, () => console.log(`Proxying to ${config.proxyBase} at 0.0.0.0:${config.port}`));
function makeMapKey({method, fullUrl, body, headers}) {
return `${method}:${fullUrl}:${body}`;
}
async function makeRequest({method, fullUrl, body, headers}) {
if (config.debug) console.debug(`new request: ${method} ${fullUrl}`);
let resp = await axios.request({
baseURL: config.proxyBase,
validateStatus(status) { return true; },
responseType: 'arraybuffer',
method,
url: fullUrl,
headers,
data: body,
});
delete resp.headers['content-length'];
delete resp.headers['transfer-encoding'];
delete resp.headers['connection'];
if (config.debug) console.debug(`response: ${resp.status} - ${fullUrl}`);
return {body: resp.data, headers: resp.headers, status: resp.status};
}