forked from geek-cetas/node.isbn.net.in
-
Notifications
You must be signed in to change notification settings - Fork 0
/
isbn.js
118 lines (102 loc) · 2.78 KB
/
isbn.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
var emitter = require('events').EventEmitter,
inherits = require('sys').inherits,
request = require('request');
var options = { host : 'isbn.net.in',
path : '/',
url : function() { return 'http://' + this.host + this.path; }}
function error(code, desc)
{
this['code'] = code;
this['desc'] = desc;
}
function Book(data)
{
// A simple bean to hold the required data
this.vendor = data[0];
this.price = data[1].price;
this.url = data[1].url;
}
function Books(books)
{
// A collection for holding a set of books
this.books = books;
/* To enable simple look up add the vendors as attributes to the class
ex : var b = getBooks();
// This will print the details of the book set by the vendor
console.log(b.flipkart);
*/
for(var i = 0; i < books.length; i++)
this[books[i].vendor] = books[i];
}
Books.prototype.count = function() { return this.books.length; };
Books.prototype.cheapest = function() {
// returns the cheapest deal from the set of books
var book;
for(var i = 0; i < this.books.length; i++)
{
if(book == null)
book = this.books[i];
else
{
if(book.price > this.books[i].price)
book = this.books[i];
}
}
return book;
}
Books.prototype.vendors = function() {
// returns a set of vendors
var vendors = new Array(this.books.length);
for(var i = 0; i < vendors.length; i++ )
vendors[i] = this.books[i].vendor;
return vendors;
}
function parse(data)
{
// parses the data which is in json format and creates a list of
// books
try
{
var json = JSON.parse(data.toString());
if(json.length === undefined)
throw "Invalid json received"
var books = new Array(json.length);
for(var i = 0; i < json.length; i++)
{
books[i] = new Book(json[i]);
}
this.emit('success', new Books(books));
}
catch(e)
{
this.emit('error', e);
}
}
function lookup(isbn)
{
// makes an http request to isbn.net.in and triggers
// the appropriate events
var $ = this;
options.path = '/' + isbn + '.json';
console.log(options.url());
request( options.url(),
function(error, response, body)
{
if (error != null)
$.emit('error', new error(-1, e));
console.log(body);
$.__parse(body);
});
}
inherits(lookup, emitter);
lookup.prototype.__parse = parse;
function search(isbn)
{
var cls = new lookup(isbn);
cls.on('error', function (e) {
console.log('ERROR: ' + e);
})
return cls;
}
var isbn = { lookup : search };
module.exports = isbn;