-
Notifications
You must be signed in to change notification settings - Fork 17
/
api.js
76 lines (63 loc) · 1.99 KB
/
api.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
const url = require('url');
const http = require('http');
const https = require('https');
const error = require("./error");
const USER_AGENT = 'Coconut/v2 NodeJSBindings/' + require("./version").VERSION;
class API {
static request(cli, method, path, data, callback) {
const coconutURL = url.parse(cli.getEndpoint());
const reqOptions = {
hostname: coconutURL.hostname,
port: coconutURL.port || (coconutURL.protocol == 'https:' ? 443 : 80),
path: require('path').join(coconutURL.path, path),
method: method,
auth: cli.api_key+':',
headers: {
'User-Agent': USER_AGENT,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
const req = (coconutURL.protocol == 'https:' ? https : http).request(reqOptions, function(res) {
res.setEncoding('utf8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function () {
var resultObject = null;
// Don't JSON parse if body is empty
// 404 errors return empty body
if(responseString.trim() != "") {
resultObject = JSON.parse(responseString);
}
if(res.statusCode > 399) {
if(res.statusCode == 400 || res.statusCode == 401) {
return callback(null, new error.CoconutError(resultObject));
} else {
return callback(null, new error.CoconutError({
"error_code": "server_error",
"message": "Server returned HTTP status " + res.statusCode
}));
}
}
if(callback) {
callback(resultObject, null);
}
});
});
req.on('error', function(e) {
if(callback) {
callback(null, new error.CoconutError({
"error_code": "request_error",
"message": e.message
}));
}
});
if(data != null) {
req.write(JSON.stringify(data));
}
req.end();
}
}
module.exports = API;