-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
302 lines (278 loc) · 8.57 KB
/
index.js
File metadata and controls
302 lines (278 loc) · 8.57 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
var fs = require('fs');
var ini = require('ini');
var http = require('http');
var https = require('https');
var util = require('util');
var url = require('url');
function getProtocolURIPort(end_point) {
var mapping = {};
parsed_url = url.parse(end_point);
if (parsed_url.protocol === "http:") {
mapping["protocol"] = "HTTP";
} else if (parsed_url.protocol === "https:") {
mapping["protocol"] = "HTTPS";
} else {
throw new Error("Error: end_point " + end_point + " does not contain a protocol (HTTP/HTTPS).");
}
mapping["uri"] = parsed_url.hostname;
if(parsed_url.port !== 'null') {
mapping["port"] = Number(parsed_url.port);
}
return mapping;
}
var PredictiveServiceClient = function(end_point, api_key, should_verify_certificate, config_file) {
this.api_key = api_key;
this.protocol = "";
if (typeof should_verify_certificate != "boolean") {
this.should_verify_certificate = false;
} else {
this.should_verify_certificate = should_verify_certificate;
}
if (config_file != null && typeof(config_file) == "string") {
var config = ini.parse(fs.readFileSync(config_file, 'utf-8'));
end_point = config['Service Info']['endpoint'];
this.api_key = config['Service Info']['api key'];
this.should_verify_certificate = config['Service Info']['verify certificate'];
}
this.setEndpoint(end_point);
this.timeout = 10000; // default to 10 seconds timeout
this.schema = -1; // schema is not set yet
}
PredictiveServiceClient.prototype.setShouldVerifyCertificate = function(verify) {
this.should_verify_certificate = verify;
}
PredictiveServiceClient.prototype.setApikey = function(api_key) {
this.api_key = api_key;
}
PredictiveServiceClient.prototype.setTimeout = function(timeout) {
this.timeout = timeout;
}
PredictiveServiceClient.prototype.setEndpoint = function(end_point) {
var protocol_uri_port = getProtocolURIPort(end_point);
if (protocol_uri_port["protocol"] == "HTTPS") {
this.setShouldVerifyCertificate(true);
this.port = 443;
} else {
this.setShouldVerifyCertificate(false);
this.port = 80;
}
this.end_point = protocol_uri_port["uri"];
this.protocol = protocol_uri_port["protocol"];
if ('port' in protocol_uri_port) {
this.port = protocol_uri_port['port'];
}
}
PredictiveServiceClient.prototype.setSchema = function(cb) {
var b = new Buffer('api_key:' + this.api_key);
var options = {
hostname: this.end_point,
port: this.port,
path: '/',
method: 'GET',
headers: {
'Authorization': 'Basic ' + b.toString('base64')
}
};
var callback = function(error, resp) {
if (resp == null) {
cb(error);
} else {
if (resp.statusCode != 200) {
throw new Error("Error connecting to Dato Predictive Service %s." % this.end_point);
} else {
if (typeof(resp.data) != "string" && 'schema_version' in resp.data) {
this.schema = resp.data.schema_version;
} else {
this.schema = 0;
}
cb(null);
}
}
}.bind(this);
this._getRequest(options, callback);
}
PredictiveServiceClient.prototype.query = function(po_name, data, callback) {
var schema_callback = function(error) {
if (error != null) {
throw new Error(error);
} else {
this._query(po_name, data, callback);
}
}.bind(this);
if (this.schema == -1) {
this.setSchema(schema_callback);
} else {
schema_callback(null);
}
}
PredictiveServiceClient.prototype._query = function(po_name, data, callback) {
var postData = "";
if (this.schema < 7) {
postData = JSON.stringify({"api_key": this.api_key, "data": data});
} else {
postData = JSON.stringify({"data": data});
}
var b = new Buffer('api_key:' + this.api_key);
var options = {
hostname: this.end_point,
port: this.port,
path: '/query/' + po_name,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length,
'Authorization': 'Basic ' + b.toString('base64')
}
};
this._postRequest(postData, options, callback);
}
PredictiveServiceClient.prototype.feedback = function(request_id, data, callback) {
var schema_callback = function(error) {
if (error != null) {
throw new Error(error);
} else {
this._feedback(request_id, data, callback);
}
}.bind(this);
if (this.schema == -1) {
this.setSchema(schema_callback)
} else {
schema_callback(null);
}
}
PredictiveServiceClient.prototype._feedback = function(request_id, data, callback) {
var postData = "";
console.log("schema:" + this.schema);
if (this.schema < 7) {
postData = JSON.stringify({"id": request_id, "api_key": this.api_key, "data": data});
} else {
postData = JSON.stringify({"id": request_id, "data": data});
}
var b = new Buffer('api_key:' + this.api_key);
var options = {
hostname: this.end_point,
port: this.port,
path: '/feedback',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length,
'Authorization': 'Basic ' + b.toString('base64')
}
};
this._postRequest(postData, options, callback);
}
PredictiveServiceClient.prototype._postRequest = function(postData, options, callback) {
var req = null;
var status_code = null;
var data = [];
var process_resp = function(res) {
status_code = res.statusCode;
res.on('data', function(d) {
data.push(d); // aggregate data
});
res.on('end', function() {
var result = data.join('');
var parsedResult = "";
var error = null;
try {
parsedResult = JSON.parse(result);
} catch (err) {
parsedResult = result;
error = err;
}
var resp = {'statusCode': status_code, 'data': parsedResult};
callback(error, resp);
});
};
if (this.protocol == "HTTPS") {
options.rejectUnauthorized = this.should_verify_certificate;
req = https.request(options, process_resp);
} else {
req = http.request(options, process_resp);
}
req.on('error', function(e) {
callback(e, null);
});
// set timeout
req.setTimeout(this.timeout);
// write data to request body
req.write(postData);
req.end();
}
PredictiveServiceClient.prototype._getRequest = function(options, callback) {
var req = null;
var status_code = null;
var data = [];
var process_resp = function(res) {
status_code = res.statusCode;
res.on('data', function(d) {
data.push(d); // aggregate data
});
res.on('end', function() {
var result = data.join('');
var parsedResult = "";
var error = null;
try {
parsedResult = JSON.parse(result);
} catch (err) {
parsedResult = result;
error = err;
}
var resp = {'statusCode': status_code, 'data': parsedResult};
callback(error, resp);
});
}.bind(this);
if (this.protocol == "HTTPS") {
options.rejectUnauthorized = this.should_verify_certificate;
req = https.request(options, process_resp);
} else {
req = http.request(options, process_resp);
}
req.on('error', function(e) {
callback(e, null);
});
// set timeout
req.setTimeout(this.timeout);
req.end();
}
PredictiveServiceClient.prototype._initConnection = function() {
var options = {
hostname: this.end_point,
port: this.port,
path: '/',
method: 'GET',
};
this._getRequest(options, function(error, resp) {
if (resp == null) {
throw new Error(error);
} else {
if (resp.statusCode != 200) {
throw new Error("Error connecting to Dato Predictive Service %s." % this.end_point);
}
}
});
}
var Client = function(arg0, arg1, arg2) {
if (!(this instanceof Client)) {
// constructor without new
var args = Array.prototype.slice.call(arguments);
var client = Object.create(Client.prototype);
return Client.apply(client, args);
}
var argsLen = arguments.length;
if (argsLen === 2 && typeof arg0 === 'string' && typeof arg1 === 'string') {
// has a valid end point and api key, defaulting verify SSL cert to false
return new PredictiveServiceClient(arg0, arg1, null, null);
} else if (argsLen === 3 && typeof arg0 === 'string' &&
typeof arg1 === 'string' && typeof arg2 === 'boolean') {
// has all three arguments valid
return new PredictiveServiceClient(arg0, arg1, arg2, null);
} else if (argsLen === 1 && typeof arg0 === 'string') {
// loading from client config
return new PredictiveServiceClient(null, null, null, arg0);
} else {
throw new Error("Error constructing Predictive Service Client. Please check your arguments.");
}
}
module.exports = Client