-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (51 loc) · 1.64 KB
/
index.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
const express = require('express');
const aws4 = require('aws4');
const URL = require('url').URL;
// Those credentials could've been just made public, if not for
// AWS User Agreement.
// So I have to set up a separate service that will hold those credentials
// and sign requests on demand.
const credentials = JSON.parse(process.env.CREDENTIALS);
const app = express();
const allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
app.get('/zone/:zone/*', async (req, res, next) => {
try {
const response = await handle(req);
res.send(response);
} catch (e) {
return next(e);
}
});
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.json({
error: err.message,
});
});
async function handle(req) {
const url = new URL(req.params[0]);
const host = url.hostname;
const path = url.pathname;
const opts = { host, path, signQuery: true };
const zoneCredentials = credentials.zone[req.params.zone];
aws4.sign(
opts,
{ accessKeyId: zoneCredentials.key, secretAccessKey: zoneCredentials.secret },
);
return 'https://' + opts.host + opts.path;
}
console.log(`process.env.PORT is ${process.env.PORT}`);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on port ${PORT}!`));