-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (72 loc) · 2.53 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const fetch = require('node-fetch');
const sprintf = require('sprintf-js').sprintf;
const path = require('path');
const mimeTypes = require('mime-types');
const apiBinaryProxy = ({apiUrl, propertyNames = {}, assumeMimeType, forwardHeaders = false, forwardQueryString = true}) => {
const handleApiResponse = (req, res,
{
[propertyNames.payload || "payload"]: payload,
[propertyNames.extension || "extension"]: extension,
[propertyNames.mime || "mime"]: mime,
[propertyNames.filename || "filename"]: filename,
...rest
}) => {
let mimeType;
if(mime) {
mimeType = mime;
} else if (extension) {
mimeType = mimeTypes.lookup(extension);
} else if (filename) {
mimeType = mimeTypes.lookup(filename);
} else {
mimeType = assumeMimeType;
}
if(!mimeType) {
// We don't know the mime type from the API response and current config says not to assume mime type so we 404
res.sendStatus(404);
return;
}
const metadata = { filename, extension, ...rest };
if(payload) {
let buffer = new Buffer.from(payload, 'base64');
res.type(mimeType);
res.append('X-ApiBinaryProxy-Metadata', JSON.stringify(metadata));
res.send(buffer);
} else {
res.status(404);
res.json(metadata);
}
}
const handleIncomingRequest = (req, res) => {
const url = new URL(sprintf(apiUrl, req.path));
if (forwardQueryString) {
// Merge query string from apiUrl with req.query
Object.keys(req.query).forEach(key => {
url.searchParams.set(key, req.query[key]);
});
}
const fetchOptions = {};
if (forwardHeaders) {
fetchOptions.headers = req.headers
}
fetch(url, fetchOptions)
.then(fetchResponse => {
if(fetchResponse.status !== 200) {
res.sendStatus(fetchResponse.status);
return undefined;
}
return fetchResponse.json();
})
.then(json => {
if (!json) {
return;
}
return handleApiResponse(req, res, json)
})
.catch((ex) => {
res.sendStatus(500);
});
}
return handleIncomingRequest;
}
module.exports = apiBinaryProxy