-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.js
60 lines (55 loc) · 1.86 KB
/
util.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
'use strict';
const http = require('http');
const util = {
getByPath(path, result) {
if (!path.length) {
return result;
}
let intermediate = result[path[0]];
if (Array.isArray(intermediate)) {
intermediate = intermediate[intermediate.length-1];
}
if (intermediate === undefined) {
return;
}
return util.getByPath(path.slice(1), intermediate);
},
fetch(url) {
return new Promise((resolve, reject) => {
try {
http.get(url, res => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
res.resume();
return reject(error);
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
let parsedData = JSON.parse(rawData);
resolve(parsedData);
} catch (e) {
reject(e.message);
}
});
}).on('error', (e) => {
reject(`Got error: ${e.message}`);
});
} catch (error) {
reject(error);
}
});
}
};
module.exports = util;