forked from kolomiichenko/graylog-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (67 loc) · 2.03 KB
/
index.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
77
78
79
80
var request = require("request");
var methods = require("./api-methods");
function serializeObjToUri(obj) {
return Object.keys(obj)
.map(function(key) {
return key + "=" + encodeURIComponent(obj[key]);
})
.join("&");
}
var Api = function(config) {
config = config || {}
const basicAuthToken = config.basicAuth ?
config.basicAuth.username + ':' + config.basicAuth.password + '@' : ''
this._uri = (config.protocol || 'http') + '://' + basicAuthToken +
(config.host || 'localhost') + ':' + (config.port || '12900') +
(config.path || '')
};
Object.keys(methods).forEach(function(mName) {
var m = methods[mName];
Api.prototype[mName] = function(parameters, path, callback) {
if (arguments.length === 1) callback = parameters;
if (arguments.length === 2) callback = path;
var computedPath = m.path;
if (typeof arguments[1] === "object") {
computedPath = m.path.replace(/{([^}]*)}/g, function(s, p) {
return path[p];
});
}
var reqUri = this._uri + computedPath;
if (m.method === "GET" && parameters) {
reqUri = reqUri + "?" + serializeObjToUri(parameters);
}
var opts = {
url: reqUri,
method: m.method,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: m.method !== "GET" && parameters ? parameters : null,
json: false
};
request(opts, function(error, response, body) {
if (body === "") body = "{}";
if (error) {
return callback([error, body]);
}
if (response.statusCode === 403) {
return callback([JSON.parse(body).message, body]);
}
var parsedBody;
try {
parsedBody = JSON.parse(body);
} catch (err) {
callback(["Bad response", err, reqUri]);
}
callback(null, parsedBody);
});
};
});
var connect = function(config, callback) {
var that = new Api(config);
return that;
};
connect.connect = connect; // backwards compatible
connect.Api = Api;
module.exports = connect;