-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestHelper.js
More file actions
260 lines (203 loc) · 7.14 KB
/
RequestHelper.js
File metadata and controls
260 lines (203 loc) · 7.14 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
'use strict';
const HTTP = require('http');
const HTTPS = require('https');
const QueryString = require('querystring');
const FileSystem = require('fs');
const URL = require('url');
const Path = require('path');
const MAX_REDIRECTS = 10;
/**
* A helper class for making HTTP requests
*
* @memberof HashBrown.Server.Helpers
*/
class RequestHelper {
/**
* Pipes the result of a get request into the original result object
*
* @param {String} url
* @param {Object} res
*/
static pipe(url, res) {
url = url.replace('HTTP://', '');
url = url.replace('HTTPS://', '');
let hostname = url.split('/')[0];
let path = url.replace(hostname, '');
try {
let externalReq = HTTP.request({
hostname: hostname,
path: path
}, (externalRes) => {
externalRes.pipe(res);
});
externalReq.end();
} catch(e) {
res.status(404).send(e.message);
}
}
/**
* Downloads a file
*
* @param {String} url
* @param {String} destination
*
* @returns {Promise} Result
*/
static download(url, destination) {
return this.request('get', url)
.then((data) => {
let stream = FileSystem.createWriteStream(destination);
stream.write(data);
stream.on('error', (e) => {
reject(e);
});
stream.on('finish', () => {
stream.close();
});
stream.on('close', () => {
resolve(data);
});
})
.catch((e) => {
if(FileSystem.existsSync(destination)) {
FileSystem.unlinkSync(destination);
}
return Promise.reject(e);
});
}
/**
* Makes a paginated request
*
* @param {String} address
* @param {Object} data
* @param {Number} maxPages
*
* @returns {Promise} Response
*/
static getPaginated(url, data = null, maxPages = 10) {
if(!data) {
data = {};
}
data.page = 0;
let combinedResult = [];
let getNext = () => {
return this.request('get', url, data)
.then((result) => {
if(!result || !Array.isArray(result) || result.length < 1) {
return Promise.resolve(combinedResult);
}
combinedResult = combinedResult.concat(result);
data.page++;
return getNext();
});
};
return getNext();
}
/**
* Makes a generic request
*
* @param {String} method
* @param {String} url
* @param {Object} data
* @param {Boolean} asQueryString
*
* @returns {Promise} Response
*/
static request(method, url, data = null, asQueryString = false) {
return new Promise((resolve, reject) => {
method = method.toUpperCase();
let contentType = 'text/plain';
if(method === 'GET') {
asQueryString = true;
}
// Convert data
if(data) {
// To query string
if(asQueryString) {
url += '?' + QueryString.stringify(data);
data = null;
// To JSON string
} else if(typeof data === 'object') {
data = JSON.stringify(data);
contentType = 'application/json';
}
}
// Parse URL
url = URL.parse(url);
let headers = {
'Accept': '*/*',
'User-Agent': 'HashBrown CMS',
'Content-Type': contentType + '; charset=utf-8',
'Host': url.hostname
};
if(data) {
headers['Content-Length'] = Buffer.byteLength(data);
}
// Makes the actual request and checks for redirects
let redirects = 0;
let makeRequest = () => {
let protocol = url.protocol === 'https:' ? HTTPS : HTTP;
let options = {
port: url.port,
host: url.hostname,
path: url.path,
method: method,
headers: headers
};
let req = protocol.request(options, (res) => {
// We're being redirected
if(res.statusCode > 300 && res.statusCode < 400 && res.headers.location) {
// Max amount of redirects detected
if(redirects >= MAX_REDIRECTS) {
return reject(new Error('Max amount of redirects exceeded'));
}
let newUrl = URL.parse(res.headers.location);
// Host name not found, prepend old one
if(!newUrl.host) {
newUrl.host = url.host;
}
url = newUrl;
redirects++;
makeRequest();
// No redirect, we reached our destination
} else {
let str = '';
res.on('data', (chunk) => {
str += chunk;
});
res.on('error', (err) => {
reject(err);
});
res.on('end', () => {
let result = str;
try {
result = JSON.parse(str);
// If response isn't JSON, just return the string
} catch(e) {
}
// Error happened
if(res.statusCode >= 400 && res.statusCode < 600) {
let error = new Error(res.statusMessage + ' (' + res.statusCode + ')\nat ' + method + ' ' + url.protocol + '//' + Path.join(url.host, url.path) + '\n\n' + str);
error.url = url;
error.statusCode = res.statusCode;
return reject(error);
}
resolve(result, res);
});
}
});
// Handle errors
req.on('error', (e) => {
e.url = url;
reject(e);
});
if(data) {
req.write(data);
}
req.end();
}
makeRequest();
});
}
}
module.exports = RequestHelper;