-
Notifications
You must be signed in to change notification settings - Fork 286
/
makeRequest.js
368 lines (294 loc) · 9.09 KB
/
makeRequest.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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
var async = require("async");
var errors = require("../errors/requestErrors");
function xmlHttpRequest() {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
pretendingNotToRequire = require;
var module = 'xmlhttprequest';
var request = pretendingNotToRequire(module).XMLHttpRequest;
return new request();
}
function makeRequest(provider, tokenOrUsername, password) {
this.provider = provider || "http://localhost:14265";
this.tokenOrUsername = tokenOrUsername;
this.password = password || false;
this.timeout = -1;
}
/**
* Set the request timeout (-1 for no timeout)
*
* @method setTimeout
* @param {integer} timeout
**/
makeRequest.prototype.setApiTimeout = function(timeout) {
this.timeout = timeout;
}
/**
* Change the HTTP provider
*
* @method setProvider
* @param {String} provider
**/
makeRequest.prototype.setProvider = function(provider) {
this.provider = provider || "http://localhost:14265";
}
/**
* creates an XMLHttpRequest Object
*
* @method open
*
* @returns {object} request
**/
makeRequest.prototype.open = function() {
var request = xmlHttpRequest();
if(this.password) {
request.open('POST', this.provider, true, this.tokenOrUsername, this.password);
} else {
request.open('POST', this.provider, true);
}
request.setRequestHeader('Content-Type','application/json');
request.setRequestHeader('X-IOTA-API-Version', '1');
if (!this.password && this.tokenOrUsername) {
//request.withCredentials = true;
request.setRequestHeader('Authorization', 'token ' + this.tokenOrUsername);
}
return request;
}
/**
* sends an http request to a specified host
*
* @method send
* @param {object} command
* @param {function} callback
**/
makeRequest.prototype.send = function(command, callback) {
var self = this;
var request = this.open();
var timeout = this.timeout;
var settled = false;
var aborted = false;
var timer;
var timeoutError = JSON.stringify({ error: 'Request timed out.' });
if (timeout > 0) {
if (request.timeout === undefined) {
// timeout is not implemented in nodejs xhr
timer = setTimeout(function() {
if (request.readyState !== 4) {
aborted = true;
request.abort();
}
}, timeout);
} else {
// in browsers, xmr has timeout property
request.timeout = timeout;
}
}
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (settled) {
return;
}
if (!aborted) {
if (timer) {
clearTimeout(timer);
}
return self.prepareResult(request.responseText.length
? request.responseText : timeoutError, command.command, callback);
}
settled = true;
self.prepareResult(timeoutError, command.command, callback);
}
}
try {
request.send(JSON.stringify(command));
} catch(error) {
return callback(errors.invalidResponse(error));
}
}
/**
* sends a batched http request to a specified host
* supports findTransactions, getBalances, getInclusionStates & getTrytes commands
*
* @method batchedSend
* @param {object} command
* @param {function} callback
**/
makeRequest.prototype.batchedSend = function (command, keys, batchSize, callback) {
var self = this
var requestStack = []
keys.forEach(function (key) {
// Create a copy to avoid mutating original params
var clone = command[key].slice()
while (clone.length) {
var batch = clone.splice(0, batchSize)
var params = {}
Object.keys(command).forEach(function (k) {
if (k === key || keys.indexOf(k) === -1) {
params[k] = k === key ? batch : command[k]
}
})
requestStack.push(params)
}
})
async.mapSeries(requestStack, function (command, cb) {
self.send(command, function (err, res) {
if (err) {
return cb(err)
}
cb(null, res)
})
}, function (err, res) {
if (err) {
return callback(err)
}
switch (command.command) {
case 'getBalances':
var balances = res.reduce(function (a, b) {
return a.concat(b.balances)
}, [])
res = res.sort(function (a, b) {
return a.milestoneIndex - b.milestoneIndex
}).shift()
res.balances = balances
callback(null, res)
break
case 'findTransactions':
var seenTxs = new Set()
if (keys.length === 1) {
return callback(null, res.reduce(function (a, b) {
return a.concat(b)
}, []).filter(function (hash) {
var seen = seenTxs.has(hash)
if (!seen) {
seenTxs.add(hash)
return true
}
return false
}))
}
var keysToTxFields = {
'bundles': 'bundle',
'addresses': 'address',
'hashes': 'hash',
'tags': 'tag'
}
callback(null, res.map(function (batch) {
return batch.filter(function (tx) {
return keys.every(function (key) {
return requestStack.some(function (command) {
return command.hasOwnProperty(key) &&
command[key].findIndex(function (value) {
return value === tx[keysToTxFields[key]]
}) !== -1
})
})
})
}).reduce(function (a, b) {
return a.concat(b)
}, []).filter(function (tx) {
if (!seenTxs.has(tx.hash)) {
seenTxs.add(tx.hash)
return true
}
return false
}))
break
default:
callback(null, res.reduce(function (a, b) {
return a.concat(b)
}, []))
}
})
}
/**
* sends an http request to a specified host
*
* @method sandboxSend
* @param {object} command
* @param {function} callback
**/
makeRequest.prototype.sandboxSend = function(job, callback) {
// Check every 15 seconds if the job finished or not
// If failed, return error
var newInterval = setInterval(function() {
var request = xmlHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
var result;
// Prepare the result, check that it's JSON
try {
result = JSON.parse(request.responseText);
} catch(e) {
return callback(errors.invalidResponse(e));
}
if (result.status === "FINISHED") {
var attachedTrytes = result.attachToTangleResponse.trytes;
clearInterval(newInterval);
return callback(null, attachedTrytes);
}
else if (result.status === "FAILED") {
clearInterval(newInterval);
return callback(new Error("Sandbox transaction processing failed. Please retry."))
}
}
}
try {
request.open('GET', job, true);
request.send(JSON.stringify());
} catch(error) {
return callback(new Error("No connection to Sandbox, failed with job: ", job));
}
}, 5000)
}
/**
* prepares the returned values from the request
*
* @method prepareResult
* @param {string} result
* @param {function} callback
**/
makeRequest.prototype.prepareResult = function(result, requestCommand, callback) {
// Result map of the commands we want to format
var resultMap = {
'getNeighbors' : 'neighbors',
'addNeighbors' : 'addedNeighbors',
'removeNeighbors' : 'removedNeighbors',
'getTips' : 'hashes',
'findTransactions' : 'hashes',
'getTrytes' : 'trytes',
'getInclusionStates' : 'states',
'attachToTangle' : 'trytes',
'wereAddressesSpentFrom': 'states',
'checkConsistency' : 'state'
}
var error;
try {
result = JSON.parse(result);
} catch(e) {
error = errors.invalidResponse(result);
result = null;
}
//
// TODO: PREPARE ERROR MESSAGES BETTER
//
if (!error && result.error) {
error = errors.requestError(result.error);
result = null;
}
if (!error && result.exception) {
error = errors.requestError(result.exception);
result = null;
}
// If correct result and we want to prepare the result
if (result && resultMap.hasOwnProperty(requestCommand)) {
// If the response is from the sandbox, don't prepare the result
if (requestCommand === 'attachToTangle' && result.hasOwnProperty('id')) {
result = result;
} else {
result = result[resultMap[requestCommand]];
}
}
return callback(error, result);
}
module.exports = makeRequest;