-
Notifications
You must be signed in to change notification settings - Fork 1
/
function.js
65 lines (54 loc) · 1.47 KB
/
function.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
const https = require('https');
const url = require('url');
class HttpError extends Error {
constructor (message, code) {
super(message);
this.code = code;
}
}
const generateDropboxUrl = param => {
if (!param || !param.startsWith('https://www.dropbox.com/')) {
throw new HttpError('Forbidden', 403);
}
const dropboxUrl = url.parse(param);
const path = dropboxUrl.path;
const pathParts = path.split('/');
pathParts.shift();
pathParts.splice(1, 0, 'raw');
const rawPath = pathParts.join('/');
return `https://${dropboxUrl.hostname}/${rawPath}`;
};
const respondWithError = (context, status, error) => {
context.res = {
body: { error },
status
};
context.done();
};
const upstreamResponseHandler = context => response => {
if (response.statusCode !== 302) {
throw new HttpError(response.statusMessage, response.statusCode);
}
context.res = {
body: null,
headers: {
'access-control-allow-origin': '*',
location: response.headers.location
},
status: response.statusCode
};
context.done();
};
module.exports = (context, { query }) => {
try {
https.get(
generateDropboxUrl(query.dropboxUrl),
upstreamResponseHandler(context)
);
} catch ({ code, message }) {
respondWithError(context, code, message);
}
};
module.exports.generateDropboxUrl = generateDropboxUrl;
module.exports.respondWithError = respondWithError;
module.exports.upstreamResponseHandler = upstreamResponseHandler;