-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
57 lines (48 loc) · 1.63 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
import express from "express";
import cors from "cors";
import axios from "axios";
import { typeCheck } from "type-check";
import build from "build-url";
const defaultOptions = {};
export default (options = defaultOptions) => {
/* placeholder sanity for future functionality */
if (!typeCheck("Object", options)) {
throw new Error(`Expected Object options, encountered ${options}.`);
} else if (Object.keys(options).length) {
throw new Error(`Expected an empty Object, encountered ${Object.keys(options).join(",")}.`);
}
return express()
.use(cors({ origin: (origin, callback) => callback(null, true) }))
.use(
async (req, res, next) => {
try {
const { path, method, headers, body, query: queryParams } = req;
const url = build(
path.substring(1),
{ queryParams },
);
const { host: ignored, ...extras } = headers;
const { data, status, headers: responseHeaders } = await axios({
url,
method: method.toLowerCase(),
headers: extras,
...(typeCheck("Object", body) && Object.keys(body).length > 0) ? { data: body } : {},
});
const { ["transfer-encoding"]: unused, ...response } = responseHeaders;
return res
.set(response)
.status(status)
.send(data);
} catch (e) {
const { response } = e;
if (response) {
const { status, data } = response;
return res
.status(status)
.json(data);
}
return next(e);
}
},
);
};