-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
112 lines (92 loc) · 2.36 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
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
var packageJSON = require('./package.json'),
util = require('util'),
program = require('commander'),
isbn = require('./src/isbn'),
async = require('async'),
_ = require('underscore'),
superagent = require('superagent');
var apiBase = 'http://api.127.0.0.1.xip.io:3000/v1/';
// var apiBase = 'http://api.openbookprices.com/v1/';
var version = packageJSON.version;
var userAgent = util.format("%s v%s", packageJSON.name, packageJSON.version);
function getJSON (url, cb) {
return superagent
.get(url)
.set("User-Agent", userAgent)
.on("error", function (err) {
console.error(err);
process.exit();
})
.end(cb);
}
program
.version(version)
.option('--country [country]', "specify the country (eg 'GB' or 'US')")
.option('--currency [currency]', "specify the currency (eg 'GBP' or 'USD')")
.usage('[options] <isbn>')
.parse(process.argv);
if (program.args.length == 0) {
program.help();
}
var isbn = isbn.clean(program.args[0]);
if (!isbn ) {
console.error("The ISBN provided is not valid: '%s'", program.args[0]);
process.exit(1);
}
var initialURL = apiBase + "books/" + isbn + "/prices";
if (program.country) {
initialURL += "/" + program.country;
if (program.currency) {
initialURL += "/" + program.currency;
}
}
getJSON(
initialURL,
handleInitialRequest
);
function handleInitialRequest (res) {
console.log(
"Fetching prices for '%s' in '%s', shipping to '%s'",
isbn,
res.body.request.currency,
res.body.request.country
);
// console.log(res.body);
async.eachLimit(
res.body.results,
6,
handleVendorRequest,
allDone
);
}
function handleVendorRequest (data, cb) {
// console.log(data);
if (data.meta.retryDelay) {
// console.log("Retrying in %s", data.meta.retryDelay);
setTimeout(
function () {
getJSON(
data.request.url,
function (res) {
handleVendorRequest(res.body, cb);
}
);
},
data.meta.retryDelay * 1000
);
} else {
_.each(data.offers, function (offer, condition) {
console.log(
"%s (%s) from %s: %s",
offer.total,
condition,
data.vendor.name,
offer.url || data.vendor.url
);
});
cb();
}
}
function allDone (err) {
console.log("all done!");
}