-
Notifications
You must be signed in to change notification settings - Fork 3
/
handleSearch.js
64 lines (58 loc) · 2.55 KB
/
handleSearch.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
'use strict';
var Flights = require('./flights');
var Promises = require('promise');
var permute = require('./permute');
var winston = require('winston');
module.exports = function(search, dates, config) {
var dryRun = config.hasOwnProperty("dryRun") && config.dryRun;
var searchPerms = permute(dates, config.from, search.to);
var f = new Flights(config);
return new Promises(function (resolve1, reject1) {
var doSearch = function (searchPerm) {
winston.debug("Searching for: " + JSON.stringify(searchPerm));
return new Promises(function (resolve2, reject2) {
var searchOptions = {
fromAirports: searchPerm.from,
toAirports: searchPerm.to,
fromDays: config.duration.from,
toDays: config.duration.to,
year: searchPerm.date.year,
month: searchPerm.date.month,
};
f.search(searchOptions).then(function (response) {
try {
var cheapestResult = f.cheapest(response.results);
if ((cheapestResult !== null && cheapestResult.priceInt <= search.threshold) || (config.showAll && !dryRun)) {
var formatted = searchOptions.fromAirports.join(",") + "-" +
searchOptions.toAirports.join(",") + " in " + searchOptions.year + "/" +
searchOptions.month + ": " + f.format(cheapestResult);
return resolve2(formatted);
}
return resolve2(null);
} catch (e) {
winston.debug("handleSearch error: " + e + ", " + e.stack);
return reject2(e);
}
}, reject2);
});
};
var execSearch = function () {
if (searchPerms.length > 0) {
doSearch(searchPerms.shift()).then(dealWithResult, function (e) {
winston.debug("Error in search, continuing with next: " + e);
execSearch(); // skips dealWithResult, execs next
});
} else {
resolve1();
}
};
var dealWithResult = function (result) {
if (result !== null) { // under threshold, print the flight
console.log(result);
}
execSearch();
};
// start the first search
execSearch();
});
};