forked from danielsmith-eu/ita-matrix-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flights.js
90 lines (80 loc) · 3.27 KB
/
flights.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
'use strict';
var request = require('request');
var Promises = require('promise');
var parseResults = require('./parseResults');
var queryBody = require('./queryBody');
var winston = require('winston');
module.exports = function(config) {
var urlBase = "http://matrix.itasoftware.com/search";
var dryRun = config.hasOwnProperty("dryRun") && config.dryRun;
var nullResults = {results: []};
var search = function(searchOptions) {
return new Promises(function (resolve, reject) {
if (dryRun) {
winston.info("* Dry run suppressed lookup of: " + JSON.stringify(searchOptions));
return resolve(nullResults);
}
var reqOptions = {
url: urlBase,
method: "POST",
body: JSON.stringify(queryBody(searchOptions)),
json: false,
headers: {
"Content-Type": "application/javascript; charset=UTF-8",
"Origin": "http://matrix.itasoftware.com",
"Referer": "http://matrix.itasoftware.com/",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
"X-GWT-Module-Base": "http://matrix.itasoftware.com/gwt/",
"X-GWT-Permutation": "CE8DC3960A9557AEA8321F1C132B8541",
},
};
var attemptsLeft = 10;
var doCall = function() {
request(reqOptions).on("response", function (response) {
if (response.statusCode !== 200) {
winston.debug("Error querying, response is: ", response.statusCode);
if (--attemptsLeft > 0) {
winston.debug("..retrying.");
doCall();
} else {
winston.debug("..max number of retries attempted, skipping.");
resolve(nullResults);
}
}
var bodyStr = "";
response.on("data", function (data) {
bodyStr += data;
}).on("end", function () {
try {
resolve(parseResults(bodyStr));
} catch (e) {
// do nothing
}
});
}).on("error", function (error) {
return reject(error);
});
};
doCall();
});
};
var cheapest = function(results) {
var cheapest = null;
results.forEach(function (result) {
if (cheapest === null || result.priceInt < cheapest.priceInt) {
cheapest = result;
}
});
return cheapest;
};
var format = function(result) {
return result.outDate.substr(0,10) + " - " + result.inDate.substr(0,10) + " (" + result.durationDays + " days): " + result.price;
};
return {
search: search,
cheapest: cheapest,
format: format,
};
};