-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathcoceclient.js
More file actions
64 lines (57 loc) · 1.6 KB
/
coceclient.js
File metadata and controls
64 lines (57 loc) · 1.6 KB
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
/* eslint-env browser */
/* global $ */
/**
* CoceClient - Client-side library for Coce cover image service
*
* Usage:
*
* var cc = new CoceClient('http://coceserver.com:8080', 'ol,gb,aws');
* cc.fetch(['isbn1','isbn2'], function(isbn, url) {
* $('#isbn_'+isbn).html('<img src="'+url+'">');
* });
*
*/
function CoceClient(url, provider) {
const founds = {}; // Private cache for already found ISBN
let notfounds = {}; // ISBN not found in Coce
this.url = url;
this.provider = provider;
this.fetch = function fetchCovers(isbns, cbUpdateUI) {
// First, find ISBNs in client-side cache
const isbntosearch = [];
$.each(isbns, (i, isbn) => {
const cachedUrl = founds[isbn];
if (cachedUrl) {
cbUpdateUI(isbn, cachedUrl);
} else if (notfounds[isbn] === undefined) {
notfounds[isbn] = 1;
isbntosearch.push(isbn);
}
});
if (isbntosearch.length === 0) {
return;
}
const { url: serviceUrl } = this;
const { provider: serviceProvider } = this;
$.ajax({
url: `${serviceUrl}/cover?id=${isbntosearch.join(',')}&provider=${serviceProvider}`,
dataType: 'jsonp',
success(urlPerISBN) {
$.each(urlPerISBN, (isbn, coverUrl) => {
delete notfounds[isbn];
founds[isbn] = coverUrl;
cbUpdateUI(isbn, coverUrl);
});
},
});
};
this.reset = function resetCache() {
Object.keys(founds).forEach((key) => {
delete founds[key];
});
notfounds = {};
};
}
// Export for use
// eslint-disable-next-line no-unused-vars
const CoceClientConstructor = CoceClient;