This repository was archived by the owner on Oct 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultibeez.js
More file actions
94 lines (88 loc) · 2.37 KB
/
multibeez.js
File metadata and controls
94 lines (88 loc) · 2.37 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// @ts-check
const http = require("http");
const fetch = require("node-fetch");
const querystring = require("querystring");
const url = require("url");
const startServer = (port, alibeezBaseUrl) => {
return http
.createServer(async (req, res) => {
const alibeezKeys = readAlibeezKeys(req);
if (!alibeezKeys) {
res.writeHead(401);
res.end();
return;
}
try {
const bodies = await Promise.all(
alibeezKeys.map(async key => {
return requestAlibeez(
buildAlibeezUrl(alibeezBaseUrl, req.url, key)
);
})
);
res.writeHead(200);
res.end(JSON.stringify(bodies));
} catch (err) {
console.error(err);
res.writeHead(err.status, { "Content-Type": "application/json" });
res.end(JSON.stringify(err));
return;
}
})
.listen(port, () => {
console.log(`listening on ${port}`);
});
};
const readAlibeezKeys = req => {
const authorizationHeader = req.headers.authorization;
if (!authorizationHeader) {
return;
}
const [, token] = authorizationHeader.match(/Bearer (.*)/) || [];
if (!token) {
return;
}
const alibeezKeys = token.split(",").filter(key => key);
if (alibeezKeys.length === 0) {
return;
}
return alibeezKeys;
};
const buildAlibeezUrl = (alibeezBaseUrl, requestedUrl, alibeezKey) => {
const requestedUrlParsed = url.parse(requestedUrl);
const alibeezBaseUrlParsed = url.parse(alibeezBaseUrl);
return url.format({
...alibeezBaseUrlParsed,
pathname: alibeezBaseUrlParsed.path + requestedUrlParsed.pathname,
search: querystring.stringify({
...querystring.parse(requestedUrlParsed.search.replace(/^\?/, "")),
...querystring.parse(alibeezBaseUrlParsed.search),
key: alibeezKey
})
});
};
const requestAlibeez = async url => {
const response = await fetch(url, {
method: "GET"
});
const isJson = response.headers
.get("Content-Type")
.startsWith("application/json");
const body = isJson ? await response.json() : null;
if (!response.ok) {
throw {
status: 504,
error: {
status: response.status,
statusText: response.statusText,
body
}
};
}
return body;
};
startServer(
process.env.PORT || 4000,
process.env.ALIBEEZ_API_BASE_URL ||
"https://dev-infra.my.alibeez.com/api/query"
);