-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
75 lines (58 loc) · 1.54 KB
/
handler.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
import * as https from 'https';
let hostname = '',
path = '',
method = '',
protocol = 'https:',
headers = {
'Content-Type': 'application/json'
};
const validMethods = [
'GET', 'POST', 'PUT',
'DELETE', 'HEAD', 'CONNECT',
'OPTIONS', 'TRACE', 'PATCH'
];
/**
* Set connection params
*
* @param options host, path and method
*/
const config = options => {
if (options.method && !validMethods.includes(options.method)) {
// the error message you always wished you could send.. don't lie, you know its true
throw new Error(`wtf??: unknown method ${options.method}... are you drunk?`);
}
// toss if not supported
if (options.method && options.method !== 'GET') {
throw new Error(`Unsupported METHOD: '${options.method}', try back later.`);
}
hostname = options.host;
path = options.path;
method = options.method ?? 'GET';
};
/**
* Handle the https request
*/
const handler = () => {
return new Promise((resolve, reject) => {
let data = '';
let options = {
protocol,
hostname,
path,
method,
headers,
};
try {
const request = https.request(options);
request.on('response', (res) => {
res.setEncoding('utf8');//<< set if fetching json unless you want raw buffer data
res.on('data', resData => data += resData);
res.on('end', () => resolve(JSON.parse(data)));
}).on('error', error => reject( error));
request.end();
} catch(e) {
reject(e);
}
});
}
export { handler, config };